The Accomodation of Students
二分图
题目大意:
有n个人,其中一些人相互认识。
佳爷需要将这n个人分成若干个小队(每个小队2人),并使得成员之间相互认识的小队数目最大。
但佳爷不是个随便的人,若无法将这n个人分成两组,且每组中的人相互不认识,那么佳爷将不会进行分队。
请问,佳爷是否需要进行分队呢?
思路:
先判断是否是二分图,用染色法,如果是二分图,用匈牙利算法找到最大匹配数,模板题。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 210;
int n, m;
int h[N], e[N * N], ne[N * N], idx;
int match[N];
bool st[N], flag;
int color[N];
void add(int x, int y)
{
e[idx] = y, ne[idx] = h[x], h[x] = idx ++;
}
bool dfs(int u, int c)
{
color[u] = c;
for(int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if(!color[j])
{
if(!dfs(j, 3 - c)) return false;
}
else if(color[j] == c) return false;
}
return true;
}
bool find(int x)
{
for(int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if(!st[j])
{
st[j] = true;
if(!match[j] || find(match[j]))
{
match[j] = x;
return true;
}
}
}
return false;
}
int main()
{
int n, m;
while(cin >> n >> m)
{
idx = 0;
memset(h, -1, sizeof h);
memset(color, 0, sizeof color);
memset(match, 0, sizeof match);
flag = true;
for(int i = 0; i < m; i ++)
{
int x, y;
cin >> x >> y;
add(x, y);
}
for(int i = 1; i <= n; i ++)
{
if(!color[i])
{
if(!dfs(i, 1))
{
flag = false;
break;
}
}
}
if(!flag) cout << "No\n";
else{
int res = 0;
for(int i = 1; i <= n; i ++)
{
memset(st, false, sizeof st);
if(find(i)) res ++;
}
cout << res << endl;
}
}
}