过山车
Problem Description
RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了。可是,过山车的每一排只有两个座位,而且还有条不成文的规矩,就是每个女生必须找个个男生做partner和她同坐。但是,每个女孩都有各自的想法,举个例子把,Rabbit只愿意和XHD或PQK做partner,Grass只愿意和linle或LL做partner,PrincessSnow愿意和水域浪子或伪酷儿做partner。考虑到经费问题,boss刘决定只让找到partner的人去坐过山车,其他的人,嘿嘿,就站在下面看着吧。聪明的Acmer,你可以帮忙算算最多有多少对组合可以坐上过山车吗?
1<=N 和M<=500.接下来的K行,每行有两个数,分别表示女生Ai愿意和男生Bj做partner。最后一个0结束输入。
Output
对于每组数据,输出一个整数,表示可以坐上过山车的最多组合数。
6
3
3
1
1
1
2
1
3
2
1
2
3
3
1
0
解题思路:
二分图匹配的模板题
另一个很相似的题目 poj 3041 Asteroids
一个写的很好的博客 http://blog.csdn.net/dark_scope/article/details/8880547
代码
#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <string.h>
#include <algorithm>
#include <set>
#include <sstream>
#include <vector>
using namespace std;
const int maxn = 1010;
const int INF = 0x3f3f3f3f;
int k,n,m;
vector<int> G[maxn];
int match[maxn];
int used[maxn];
bool dfs(int v){
used[v] = true;
for(int i = 0; i<G[v].size();++i){
int u = G[v][i];
int w = match[u];
///如果这个男生被匹配过了,并且曾经没有尝试给他换匹配,并且更换匹配可行
if(w<0 || !used[w] && dfs(w)){
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int matchRes(){
int res = 0;
memset(match,-1,sizeof(match));
for(int v = 0; v<m+n; ++v){
if(match[v]<0){
memset(used,0,sizeof(used));
if(dfs(v))
res++;
}
}
return res;
}
int main()
{
while(scanf("%d",&k)!=EOF && k!=0){
scanf("%d%d",&m,&n);
for(int i = 0; i<maxn; ++i)
G[i].clear();
for(int i =0;i<k;++i){
int u,v;
scanf("%d%d",&u,&v);
///女生编号从1 ~ m,男生从m+1 ~ m+n
G[u-1].push_back(v-1+m);
G[v-1+m].push_back(u-1);///减去1是因为图存的是从0开始
}
printf("%d\n",matchRes());
}
return 0;
}