HDU - 2444 The Accomodation of Students(二分图判断加匈牙利算法)

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<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs.

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

Sample Output

No
3

匈牙利算法讲解推荐这位大神的博客:http://blog.csdn.net/dark_scope/article/details/8880547

代码:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = 205;

bool board[MAXN][MAXN];
int color[MAXN];
int N,M;

bool Judge(int x){
	for(int i=1 ; i<=N ; ++i){
		if(board[x][i] == 0)continue;
		if(color[x] == color[i])return false;
		if(color[i] == 0){
			color[i] = 3-color[x];
			if(!Judge(i))return false;
		}
	}
	return true;
}

int pre[MAXN];
bool used[MAXN];

int Find(int x){
	for(int i=1 ; i<=N ; ++i){
		if(board[x][i]){
			if(used[i])continue;
			used[i] = true;
			if(pre[i] == 0 || Find(pre[i])){
				pre[i] = x;
				return 1;
			}
		}
	}
	return 0;
}

int main(){
	
	while(scanf("%d %d",&N,&M)!=EOF){
		memset(board,false,sizeof board);
		memset(color,0,sizeof color);
		while(M--){
			int a,b;
			scanf("%d %d",&a,&b);
			board[a][b] = board[b][a] = true;
		}
		color[1] = 1;
		if(!Judge(1)){
			printf("No\n");
			continue;
		}
		memset(pre,0,sizeof pre);
		int sum = 0;
		for(int i=1 ; i<=N ; ++i){
			memset(used,false,sizeof used);
			sum += Find(i);
		}
		printf("%d\n",sum/2);
	}
	
	return 0;
}

 

posted @ 2018-07-17 17:14  Assassin_poi君  阅读(140)  评论(0编辑  收藏  举报