题目链接http://acm.hdu.edu.cn/showproblem.php?pid=2444
题意:
有一组学生(点),他们之间有相互认识的关系(边),问能否分成两组使得组内没有相识的人,不能的话输出“No”,注意不是“NO”,因为这个wa了半天=_=,如果能的话则对他们安排住宿,使得两个相互认识的人住在一个双人间里,问需要多少个双人间。
分析:
分组就是二分图判定,安排住宿就是二分图最大匹配。
二分图判定可参考我另一片博客:https://blog.youkuaiyun.com/qq_36501006/article/details/81138981
#include <bits/stdc++.h>
#define fp(PP,QQ,RR) for(int PP = QQ;PP < RR;PP ++)
#define MAXN 205
using namespace std;
int m,n,color[MAXN];
vector <int> G[MAXN];
int match[MAXN];
bool used[MAXN];
void addedge(int u,int v){
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int v){
used[v] = 1;
fp(i,0,G[v].size()){
int u = G[v][i],w = match[u];
if(w < 0 || !used[w] && dfs(w)){
match[v] = u;
match[u] = v;
return 1;
}
}
return 0;
}
int bipartite_matching(int V){
int res = 0;
memset(match,-1,sizeof(match));
fp(v,1,V + 1){
if(match[v] < 0){
memset(used,0,sizeof(used));
if(dfs(v)) res ++;
}
}
return res;
}
bool is(){
queue <int> q;
memset(color,0,sizeof(color));
q.push(1);
color[1] = 1;
int cnt = 0;
while(!q.empty()){
int p = q.front(); q.pop();cnt ++;
fp(i,0,G[p].size()){
if(color[G[p][i]] == color[p]){
return 0;
}
else{
if(!color[G[p][i]]){
color[G[p][i]] = 3 - color[p];
q.push(G[p][i]);
}
}
}
}
return 1;
}
int main(void){
while(scanf("%d%d",&n,&m) != EOF){
int a,b;
fp(i,0,m){
scanf("%d%d",&a,&b);
addedge(a,b);
}
if(!is() || n == 1) puts("No");
else cout << bipartite_matching(n) << endl;
fp(i,0,MAXN){
G[i].clear();
}
}
return 0;
}