HDU2444 The Accomodation of Students(二分匹配 匈牙利算法)

来源:互联网 发布:java下载 编辑:程序博客网 时间:2024/05/01 11:26

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 41 21 31 42 36 51 21 31 42 53 6
 

Sample Output
No3
 

Source

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;#define N 205int a[N][N],vis[N],link[N];int n,m;bool bfs(){int i,j;queue<int>q;for(i=1;i<=n;i++){if(vis[i]!=-1) continue;vis[i]=1;q.push(i);while(!q.empty()){int cur=q.front();q.pop();for(j=1;j<=n;j++)if(a[cur][j]){if(vis[j]==vis[cur]) return false;if(vis[j]==-1){vis[j]=(vis[cur]+1)%2;q.push(j);}}}}return true;}bool dfs(int x){int i,j;for(i=1;i<=n;i++)if(a[x][i]&&!vis[i]){vis[i]=1;if(link[i]==0||dfs(link[i])){link[i]=x;return true;}}return false;}int main(){int i,j;while(~scanf("%d%d",&n,&m)){memset(a,0,sizeof(a));    int e,s;    while(m--){scanf("%d%d",&s,&e);a[e][s]=a[s][e]=1;}memset(vis,-1,sizeof(vis));if(!bfs()){printf("No\n");continue;}int ans=0;memset(link,0,sizeof(link));for(i=1;i<=n;i++){memset(vis,0,sizeof(vis));if(dfs(i)) ans++;}printf("%d\n",ans/2);}return 0;}




0 0
原创粉丝点击