HDU 2444 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<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
分析:无向图G为二分图的重要条件是,G中至少有两个顶点,且其所有回路的长度为偶数,即存在奇数环的话,G就不是二分图。
判断二分图的方法:染色法
把图中的点染成黑白两色。 首先取一个点染成白色,然后将其相邻的点染成黑色,如果发现有相邻的且同色的点,则说明图G 不是二分图。
二分图最大匹配:匈牙利算法,因为以任意一个集合为准求得的匹配数相等,所以可以不把原集合分开,最后结果减半。

code:

View Code
#include<stdio.h>
#include<string.h>
#define clr(x) memset(x,0,sizeof(x))
#define maxn 202
int n,m,flag;
bool g[maxn][maxn];
bool v[maxn];
int c[maxn]; //颜色,0表示还没有访问,1表示黑色,-1表示白色
int link[maxn];
void dfs(int i,int color) // 染色法判断G是否为二分图
{
int j;
for(j=1;j<=n;j++)
{
if(g[i][j])
{
if(c[j]==0)
{
c[j]=-color;
dfs(j,-color);
}
else if(c[j]==color)
{
flag=0;
return;
}
if(flag==0)
return;
}
}
}
int check()
{
flag=1;
clr(c);
c[1]=1; //设一号是黑色,将其相邻的点染成白色
dfs(1,1); //从一号开始染色
return flag;
}
bool find(int k)
{
int i;
for(i=1;i<=n;i++)
{
if(g[k][i]&&!v[i])
{
v[i]=1;
if(link[i]==0||find(link[i]))
{
link[i]=k;
return 1;
}
}
}
return 0;
}
int main()
{
int i,tot,p,q;
while(scanf("%d%d",&n,&m)!=EOF)
{
clr(g); clr(link);
while(m--)
{
scanf("%d%d",&p,&q);
g[p][q]=g[q][p]=1;
}
if(!check())
{
printf("No\n");
continue;
}
tot=0;
for(i=1;i<=n;i++)
{
clr(v);
if(find(i))
tot++;
}
printf("%d\n",tot/2);
}
return 0;
}




posted @ 2012-03-15 00:57  'wind  阅读(246)  评论(0编辑  收藏  举报