The Accomodation of Students
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
题目大意:
Google翻译:
有一群学生。他们中的一些人可能彼此认识,而其他人则不认识。例如,A和B彼此了解,B和C彼此了解。但这并不意味着A和C互相认识。
现在,您将获得彼此了解的所有学生对。你的任务是将学生分成两组,以便同一组中的任何两个学生彼此不认识。如果这个目标可以实现,那么将他们安排到双人房。请记住,只有出现在上一组中的巴黎才能住在同一个房间,这意味着只有已知的学生才能住在同一个房间。
计算可以安排到这些双人房间的最大对数。
输入
对于每个数据集:
第一行给出两个整数,n和m(1 <n <= 200),表明有n个学生和m对学生互相认识。接下来的m行给出了这样的对。
继续到文件的末尾。
输出
如果这些学生不能分成两组,则打印“No”。否则,打印可在这些房间中排列的最大对数。
个人理解:n个点m条边,判断这个图是不是二分图,如果不是输出No,如果是就输出最大匹配数。
思路:模板题,先用染色法判断是不是二分图,再用匈牙利算法求最大匹配数
没学过匈牙利算法的可以看这篇,讲的很清楚:https://blog.youkuaiyun.com/dark_scope/article/details/8880547
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define N 505
int color[N],vis[N],match[N],n,m,pre;
vector<int>a[N];
int judge()
{
queue<int>q;
q.push(pre);
color[pre]=1;
while(!q.empty())
{
int x=q.front();
q.pop();
for(int i=0; i<a[x].size(); i++)
{
int v=a[x][i];
if(color[v]==0)
{
color[v]=-color[x];
q.push(v);
}
else if(color[v]==color[x]) return 0;
}
}
return 1;
}
int find(int x)
{
for(int i=0; i<a[x].size(); i++)
{
int v=a[x][i];
if(!vis[v])
{
vis[v]=1;
if(match[v]==0||find(match[v]))
{
match[v]=x;
return 1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0; i<=n; i++) a[i].clear();
mem(match,0);
mem(color,0);
pre=0;
int x,y;
for(int i=0; i<m; i++)
{
scanf("%d%d",&x,&y);
if(!pre) pre=x;
a[x].push_back(y);
a[y].push_back(x);
}
if(!judge())printf("No\n");
else
{
int sum=0;
for(int i=1; i<=n; i++)
{
mem(vis,0);
if(find(i))sum++;
}
printf("%d\n",sum/2);
}
}
return 0;
}