您的位置:首页 > 其它

hdu 2444(二分图最大匹配,判断是否二分图)

2018-02-14 22:34 393 查看
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

题解:

先是要判断是否为二部图,然后求最大匹配。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int MAXN = 202;
vector<int> EV[MAXN];
int linker[MAXN];
bool used[MAXN];
int uN;
int matchs[MAXN],cnt[MAXN];

bool dfs(int u)
{
int i;
for(i=0;i<EV[u].size();i++)
{
int v = EV[u][i];
if(!used[v])
{
used[v]=true;
if(linker[v]==-1||dfs(linker[v]))
{
linker[v]=u;
return true;
}

}
}
return false;
}

int hungary()
{
int res=0;
int u;
memset(linker,-1,sizeof(linker));
for(u=1;u<=uN;u++)
{
memset(used,false,sizeof(used));
if(dfs(u)) res++;
}
return res;
}

bool judge(int x,int y)
{
int i;
for(i=0;i<EV[x].size();i++)
{
if(cnt[EV[x][i]]==0)
{
cnt[EV[x][i]]=-1*y;
matchs[EV[x][i]]=true;
if(!judge(EV[x][i],-1*y)) return false;
}
else if(cnt[EV[x][i]]==y)  return false;
}
return true;
}

bool matched()
{
int i;
memset(matchs,false,sizeof(matchs));
for(i=1;i<=uN;i++)
{
if(EV[i].size()&&!matchs[i])
{
memset(cnt,0,sizeof(cnt));
cnt[i]=-1;
matchs[i]=true;
if(!judge(i,-1)) return false;
}
}
return true;
}

int main()
{
int m;
int i;
int u,v;
while(scanf("%d%d",&uN,&m)!=EOF)
{
for(i=1;i<=uN;i++)
{
if(EV[i].size()) EV[i].clear();
}
while(m--)
{
scanf("%d%d",&u,&v);
EV[u].push_back(v);
EV[v].push_back(u);
}
if(matched()) printf("%d\n",hungary()/2);
else printf("No\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: