题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=2444
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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.
The first line gives two integers, n and m(1<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs.
Proceed to the end of file.
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#define MAX 203
using namespace std;
//匈牙利算法 - st
int n,m;
struct Edge{
int u,v;
};
vector<Edge> E;
vector<int> G[MAX];
int matching[MAX];
int vis[MAX];
void init(int l,int r)
{
E.clear();
for(int i=l;i<=r;i++) G[i].clear();
}
void add_edge(int u,int v)
{
E.push_back((Edge){u,v});
E.push_back((Edge){v,u});
int _size=E.size();
G[u].push_back(E.size()-);
G[v].push_back(E.size()-);
}
bool dfs(int u)
{
for(int i=,_size=G[u].size();i<_size;i++)
{
int v=E[G[u][i]].v;
if (!vis[v])
{
vis[v]=;
if(!matching[v] || dfs(matching[v]))
{
matching[v]=u;
matching[u]=v;
return true;
}
}
}
return false;
}
int hungarian()
{
int ret=;
memset(matching,,sizeof(matching));
for(int i=;i<=n;i++)
{
if(!matching[i])
{
memset(vis,,sizeof(vis));
if(dfs(i)) ret++;
}
}
return ret;
}
//匈牙利算法 - ed
bool judge()
{
memset(vis,,sizeof(vis));
queue<int> q;
q.push();
vis[]=;
while(!q.empty())
{
int now=q.front();q.pop();
for(int i=,_size=G[now].size();i<_size;i++)
{
int nex=E[G[now][i]].v;
if(!vis[nex])
{
q.push(nex);
vis[nex]=-vis[now];
}
if(vis[nex]==vis[now]) return false;//不是二分图
}
}
return true;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init(,n);
for(int i=,u,v;i<=m;i++)
{
scanf("%d%d",&u,&v);
add_edge(u,v);
add_edge(v,u);
}
if(!judge()) printf("No\n");
else printf("%d\n",hungarian());
}
}
PS.这里因为懒得枚举U集里的点(因为这要先得到U集里的点都是哪些),所以直接枚举所有点;