月老的难题
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
月老准备给n个女孩与n个男孩牵红线,成就一对对美好的姻缘。
现在,由于一些原因,部分男孩与女孩可能结成幸福的一家,部分可能不会结成幸福的家庭。
现在已知哪些男孩与哪些女孩如果结婚的话,可以结成幸福的家庭,月老准备促成尽可能多的幸福家庭,请你帮他找出最多可能促成的幸福家庭数量吧。
假设男孩们分别编号为1~n,女孩们也分别编号为1~n。
-
输入
-
第一行是一个整数T,表示测试数据的组数(1<=T<=400)
每组测试数据的第一行有两个整数n,K,其中男孩的人数与女孩的人数都是n。(n<=500,K<=10 000)
随后的K行,每行有两个整数i,j表示第i个男孩与第j个女孩有可能结成幸福的家庭。(1<=i,j<=n)
输出
- 对每组测试数据,输出最多可能促成的幸福家庭数量 样例输入
-
1 3 4 1 1 1 3 2 2 3 2
样例输出
-
2
-
第一行是一个整数T,表示测试数据的组数(1<=T<=400)
匈牙利算法求二分图的最大匹配数,万幸发现了http://blog.youkuaiyun.com/dark_scope/article/details/8880547,然后算法才变得不那么无聊了。。。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 555;
vector <int> g[maxn];
int T, n, k;
int from[maxn], tot;
bool use[maxn];
bool match(int x) {
for(unsigned i = 0; i < g[x].size(); i++) {
if(!use[g[x][i]]) {
use[g[x][i]] = true;
if(from[g[x][i]] == -1 || match(from[g[x][i]])) {
from[g[x][i]] = x;
return true;
}
}
}
return false;
}
int hungary() {
tot = 0;
memset(from, 255, sizeof(from));
for(int i = 1; i <= n; i++) {
memset(use, false, sizeof(use)); //为什么每次都要清空有点理解无能
if(match(i)) tot++;
}
return tot;
}
int main() {
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; i++) {
g[i].clear();
}//清空vector
int boy, girl;
while(k--) {
scanf("%d%d", &boy, &girl);
g[boy].push_back(girl);
}
printf("%d\n", hungary());
}
return 0;
}
因为有多组数据却忘了每次要清空vector, 然后各种wa /(ㄒoㄒ)/~~