The Accomodation of Students(判断二分图以及求二分图最大匹配)

The Accomodation of Students

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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
 
题意:判断给出的图是否是二分图,如果是,则求出最大匹配。
 
解法:判断是否是二分图可以用染色法,标记相邻的点为不同颜色,如果标记途中发现要标记的两个点是相同颜色的,则说明这个图不是二分图。如果没遇到这种情况,就说明是二分图。
还有一种判断方法,就是用并查集,具体可以参考:http://www.cnblogs.com/scaugsh/p/5533202.html
 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
using namespace std;
int n,m;
int f[];
int A[],B[],match[],book[];
vector <int> V[];//邻接表储存边的关系
void init()
{
memset(match,,sizeof(match));
for (int i=;i<=n;i++)
V[i].clear();
for (int i=; i<=*n; i++)
f[i]=i;
}
int find(int x)
{
int r=x,i=x,t;
while (r!=f[r]) r=f[r];
while (i!=r)
{
t=f[i];
f[i]=r;
i=t;
}
return r;
}
void mix(int x,int y)
{
int fx=find(x),fy=find(y);
f[fx]=fy;
}
bool IsTwo()//染色法求二分图
{
memset(book,,sizeof(book));
queue <int> Q;
Q.push();
book[]=;
while (!Q.empty())
{
int temp=Q.front();
Q.pop();
for (int i=;i<V[temp].size();i++)
{
int num=V[temp][i];
if (book[num]==)
{
book[num]=-book[temp];
Q.push(num);
}
else if (book[num]==book[temp]) return ;
}
}
return ;
}
int dfs(int u)
{
for (int i=; i<V[u].size(); i++)
{
int pos=V[u][i];
if (book[pos]==)
{
book[pos]=;
if (match[pos]==||dfs(match[pos]))
{
match[pos]=u;
return ;
}
}
}
return ;
}
int solve()
{
int ans=;
for (int i=; i<=n; i++)
{
memset(book,,sizeof(book));
if (dfs(i)) ans++;
}
return ans;
}
int main()
{
int a,b;
while (scanf("%d%d",&n,&m)>)
{
init();
int ok=;
while (m--)
{
scanf("%d%d",&a,&b);
if (find(a)==find(b))
ok=;
if (ok)
{
mix(a,b+n);
mix(b,a+n);
V[a].push_back(b);
V[b].push_back(a);
}
}
if (!ok)
{
puts("No");
continue;
}
/*if (!IsTwo())
{
puts("No");
continue;
}*/
printf("%d\n",solve()/);
}
return ;
}
 
上一篇:Java8 lambda表达式10个示例<转>


下一篇:SDUT OJ 数据结构实验之二叉树七:叶子问题