hdu2444 最大匹配(染色法bfs二分图的判断)

The Accomodation of Students

Problem Description
There are a group of students. Some of them may know each other, while others don't. For example, A and B know each other, B and C know each other. But this may not imply that A and C know each other.

Now you are given all pairs of students who know each other. Your task is to divide the students into two groups so that any two students in the same group don't know each other.If this goal can be achieved, then arrange them into double rooms. Remember, only paris appearing in the previous given set can live in the same room, which means only known students can live in the same room.

Calculate the maximum number of pairs that can be arranged into these double rooms.

Input
For each data set:
The first line gives two integers, n and m(1

Proceed to the end of file.


Output
If these students cannot be divided into two groups, print "No". Otherwise, print the maximum number of pairs that can be arranged in those rooms.

Sample Input
4 4

1 2

1 3

1 4

2 3

6 5

1 2

1 3

1 4

2 5

3 6

题目大意:有n个人,然后有m对认识的关系,然后让你判断是否可以讲这些人分成两个组,每个组要求组内的人要相互不认识才行,如果可以的话就是求出最大的两组的对数

分析:首先就需要去判断给出的这个关系是否可以构成一个二分图

判断二分图方法:用染色法,把图中的点染成黑色和白色。
首先取一个点染成白色,然后将其相邻的点染成黑色,如果发现有相邻且同色的点,那么就退出,可知这个图并非二分图。

依据这个就需要用一个队列求解了,对与二分图的最大匹配问题,因为是一个无向图,因此就是需要将所得到的结果除以2,就是这个二分图的最大匹配了

#include
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define me(a,b) memset(a,b,sizeof a)
int n,m;
int sy[300],vis[300];
int e[300][300],str[300][300];
int dfs(int u){
    rep(i,1,n){
        if(!vis[i]&&e[u][i]){
            vis[i]=1;
            if(!sy[i]||dfs(sy[i])){
                sy[i]=u;
                return 1;
            }
        }
    }
    return 0;
}
int solve(){
    me(sy,0);
    int ans=0;
    rep(i,1,n){
        me(vis,0);
        ans+=dfs(i);
    }
    return ans;
}
bool check(){//判断是否是二分图
    me(vis,0);
    vis[1]=1;
    queueq;
    q.push(1);
    while(q.size()){
        int u=q.front();
        q.pop();
        for(int i=1;i<=n;i++)
        {
            if(e[u][i]){
                if(!vis[i]){
                if(vis[u]==1)
                    vis[i]=2;
                else
                    vis[i]=1;
                    q.push(i);
                }
                if(vis[u]==vis[i]) return false;
            }
        }
    }
    return true;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    while(scanf("%d%d",&n,&m)!=EOF){
        me(e,0);
        me(str,0);
        rep(i,1,m){int u,v;
        scanf("%d%d",&u,&v);
        e[v][u]=e[u][v]=1;
        }
        if(!check()){
            printf("No\n");
            continue;
        }
        printf("%d\n",solve()/2);
   }
    return 0;
}

 

你可能感兴趣的:(二分图)