题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444
就是一个匈牙利算法模板题。
代码:
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n,m;
int e[205][205];
int col[205];
int match[205];
int v[205];
void init()
{
memset(col,-1,sizeof(col));
memset(e,0,sizeof(e));
memset(match,0,sizeof(match));
}
void input()
{
for(int i = 0;i < m;++i)
{
int a,b;
scanf("%d%d",&a,&b);
e[a][b] = e[b][a] = 1;
}
}
bool bfs(int s)
{
queue<int> q;
q.push(s);
col[s] = 1;
while(!q.empty())
{
int head = q.front();
q.pop();
for(int i = 1;i <= n;++i)
{
if(e[head][i] && col[i] == -1)
{
col[i] = !col[head];
q.push(i);
}
if(e[head][i] && col[i] == col[head])
return false;
}
}
return true;
}
bool isBiGraph()
{
bool flag = true;
for(int i = 1;i <= n;++i)
{
if(col[i] == -1 && !bfs(i))
{
flag = false;
break;
}
}
return flag;
}
bool dfs(int u)
{
for(int i = 1;i <= n;++i)
{
if(!v[i] && e[u][i] == 1)
{
v[i] = 1;
if(match[i] == 0 || dfs(match[i]))
{
match[i] = u;
//match[u] = i;
return true;
}
}
}
return false;
}
int MaxMatch()
{
int ans = 0;
for(int i = 1;i <= n;++i)
{
memset(v,0,sizeof(v));
if(dfs(i))
ans++;
}
return ans;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
input();
if(!isBiGraph())
printf("No\n");
else
{
printf("%d\n",MaxMatch() / 2);
}
}
return 0;
}