题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1083
匈牙利算法看起来比较简单,就是若找到后来者匹配点未配对直接返回配对成功,若找到的后来者匹配点已经被匹配,则取找该点的配对者是否能换点配对,如果能则后来者成功配对,前者则更换了配对点,否则后来者配对失败。因此可以在确保已经配对成功的保持配对成功的状态下,来判断后来者能否成功配对,据此递归。
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 310;
int T, P, N, count, st;
int G[maxn][maxn], vis[maxn], match[maxn];
bool dfs(int x) {
for (int i = 1; i <= N; i++) {
if (!vis[i] && G[x][i]) {
vis[i] = 1;
if (!match[i] || dfs(match[i])) {
match[i] = x;
return true;
}
}
}
return false;
}
int main(void) {
scanf("%d", &T);
while (T--){
scanf("%d%d", &P, &N);
memset(G, 0, sizeof(G));
memset(match, 0, sizeof(match));
for (int i = 1; i <= P; i++) {
scanf("%d", &count);
while (count--){
scanf("%d", &st);
G[i][st] = 1;
}
}
int flag = 0;
for (int i = 1; i <= P; i++) {
memset(vis, 0, sizeof(vis));
if (!dfs(i)) { flag = 1; break; }
}
printf("%s\n", flag ? "NO" : "YES");
}
return 0;
}