原文链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444
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
题意翻译:
有n个关系,他们之间某些人相互认识。这样的人有m对。
你需要把人分成2组,使得每组人内部之间是相互不认识的。
如果可以,就可以安排他们住宿了。安排住宿时,住在一个房间的两个人应该相互认识。
最多的能有多少个房间住宿的两个相互认识。
有多少测试数据
每组测试数据,第一行两个整数n和m。
接下来m行,每行两个整数,表示一对认识的人。
如果不能分成两组,输出No
如果可以,输出最多有多少个房间内两个人是相互认识。
题意是比较好理解的,而且也很容易建图,主要难度在于怎样判断是否是二分图。
我用的是染色的方法,其实就是对图每个点进行一次BFS,BFS的同时进行染色,只染黑白两种颜色。如果发现与点直接相连的点颜色相同,那么证明不是二分图(一个节点肯定不是二分图)。而且是无向图,最大匹配数要除2。这个很好证明,想一下应该就清楚了。
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int G[205][205],visited[205],nxt[205],color[205];
int n,m;
bool bfs(int s){
queue<int> q;
color[s]=1;
q.push(s);
while(!q.empty()){
int from=q.front();
q.pop();
for(int i = 1;i<=n;i++){
if(G[from][i]&&!color[i]){
color[i]=-color[from];
q.push(i);
}
if(G[from][i]&&color[from]==color[i]){
return false;
}
}
}
return true;
}
bool IsTwo()
{
memset(color,0,sizeof(color));
for(int i = 1;i<=n;i++)
if(!color[i]&&!bfs(i))
return false;
return true;
}
bool find(int x){
for(int i = 1;i<=n;i++){
if(!visited[i]&&G[x][i]){
visited[i]=1;
if(!nxt[i]||find(nxt[i])){
nxt[i]=x;
return true;
}
}
}
return false;
}
int match(){
memset(nxt,0,sizeof(nxt));
int sum=0;
for(int i = 1;i<=n;i++){
memset(visited,0,sizeof(visited));
if(find(i)) sum++;
}
return sum;
}
int main(int argc, char** argv) {
while(cin>>n>>m){
memset(G,0,sizeof(G));
while(m--){
int x,y;
cin>>x>>y;
G[x][y]=G[y][x]=1;
}
if(!IsTwo()||n<=1) cout<<"No"<<endl;
else cout<<match()/2<<endl;
}
return 0;
}
有关二分图匹配的知识和资料可以参考我的这篇文章:https://blog.youkuaiyun.com/qq_43472263/article/details/96831025