您的位置:首页 > 其它

hdu 2444 The Accomodation of Students 二分图判断 + 最大匹配

2014-07-17 20:03 519 查看
题目链接

题意:给定n个点,m条无向边。首先判断能否得到一个二分图(BFS),如果可以,则进行二分图匹配。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 205;
const int Mod = 1000000007;
int n,m;
bool vis[maxn];
int cx[maxn],cy[maxn];
int map[maxn][maxn],c[maxn];
bool bipartite( int u )
{
for( int i = 1; i <= n; i ++ )
{
if( map[u][i] )
{
if( c[u] == c[i] )	return false;
if( !c[i] )
{
c[i] = 3 - c[u];
if( !bipartite(i) )
return false;
}
}
}
return true;
}
int findpath( int u )
{
for( int i = 1; i <= n; i ++ )
{
if( c[i] == 2 && map[u][i] && !vis[i] )
{
vis[i] = 1;
if( cy[i] == -1 || findpath( cy[i] ) )
{
cy[i] = u;
cx[u] = i;
return true;
}
}
}
return false;
}
int MaxMatch()
{
int ans = 0;
memset( cx,-1,sizeof(cx) );
memset( cy,-1,sizeof(cy) );
for( int i = 1; i <= n; i ++ )
{
if( c[i] == 1 && cx[i] == -1 )
{
memset( vis,0,sizeof(vis) );
ans += findpath( i );
}
}
return ans;
}
int main()
{
int a,b;
while( scanf("%d%d",&n,&m) != EOF )
{
memset( c,0,sizeof(c) );
memset( map,0,sizeof(map) );
for( int i = 0; i < m; i ++ )
{
scanf("%d%d",&a,&b);
map[a][b] = map[b][a] = 1;
}
int ok = 1;
for( int i = 1; i <= n; i ++ )
{
if( c[i] == 0 )	c[i] = 1;
if( !bipartite( i ) )
ok = 0;
}
if( ok )
{
printf("%d\n",MaxMatch());
}
else
puts("No");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐