您的位置:首页 > 其它

hdu 2444 The Accomodation of Students 判断是否为二分图+最大匹配

2015-04-28 10:05 711 查看

The Accomodation of Students

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3042 Accepted Submission(s): 1425



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<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


判断是否为二分图的方法是染色,当一个结点有两种不同的颜色时,则该图必定不是二分图。
最大匹配用的是匈牙利算法。
代码:
#include <cstdio>
#include <queue>
#include <cstring>
#define SIZE 250

using namespace std ;

int col[SIZE] , pre[SIZE] , n , m;
bool vis[SIZE] , map[SIZE][SIZE] ;

bool bfs()
{
	queue<int> que ;
	que.push(1) ;
	col[1] = 1 ;
	while(!que.empty())
	{
		int now = que.front() ;
		que.pop() ;
		for(int i = 1 ; i <= n ; ++i)
		{
			if(map[now][i])
			{
				if(col[now] == col[i])
					return false ;
				else if(col[i] == 0)
				{
					col[i] = -col[now] ;
					que.push(i) ;
				}
			}
		}
	}
	return true ;
}
int find(int pos)
{
	for(int i = 1 ; i <= n ; ++i )
	{
		if(!vis[i] && map[pos][i])
		{
			vis[i] = true ;
			if(pre[i] == -1 || find(pre[i]))
			{
				pre[i] = pos ;
				return 1 ;
			}
		}
	}
	return 0 ;
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		memset(map,false,sizeof(map)) ;
		memset(pre,-1,sizeof(pre)) ;
		memset(col,0,sizeof(col)) ;
		for(int i = 0 ; i < m ; ++i)
		{
			int x, y ;
			scanf("%d%d",&x,&y);
			map[x][y] = true ;
		}
		if(!bfs())
			puts("No") ;
		else
		{
			int cnt = 0 ;
			for(int i = 1 ; i <= n ; ++i)
			{
				memset(vis,false,sizeof(vis));
				cnt += find(i) ;
			}
			printf("%d\n",cnt) ;
		}
	}
	return 0 ;
}


与君共勉
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐