原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1083
题意:p个课程,n个学生,每门课程都有若干个学生,问是否可以让每门课程都有课代表,可以输出YES。
直接用HK算法就可以,当然这题有点水,用匈牙利也可以。
#define _CRT_SECURE_NO_DEPRECATE
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#define INF 99999999;
using namespace std;
int t;
int dis;
int p, n;
int a[105][305];
int cx[305];
int cy[305];
int dx[305];
int dy[305];
bool vis[305];
bool searchPath()
{
queue<int> Q;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
dis = INF;
for (int i = 1; i <= p; i++)
{
if (cx[i] == -1)
{
Q.push(i);
dx[i] = 0;
}
}
while (!Q.empty())
{
int u = Q.front();
Q.pop();
if (dx[u] > dis)
break;
for (int v = 1; v <= n; v++)
{
if (a[u][v] && dy[v] == -1)
{
dy[v] = dx[u] + 1;
if (cy[v] == -1)
dis = dy[v];
else
{
dx[cy[v]] = dy[v] + 1;
Q.push(cy[v]);
}
}
}
}
return dis != INF;
}
int findPath(int u)
{
for (int v = 1; v <= n; v++)
{
if (!vis[v] && a[u][v] && dy[v] == dx[u] + 1)
{
vis[v] = 1;
if (cy[v] != -1 && dy[v] == dis)
continue;
if (cy[v] == -1 || findPath(cy[v]))
{
cy[v] = u;
cx[u] = v;
return 1;
}
}
}
return 0;
}
int maxMatch()
{
int ans = 0;
memset(cx, -1, sizeof(cx));
memset(cy, -1, sizeof(cy));
while (searchPath())
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= p; i++)
{
if (cx[i] == -1)
ans += findPath(i);
}
}
return ans;
}
int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &p, &n);
memset(a, 0, sizeof(a));
for (int i = 1; i <= p; i++)
{
int num, x;
scanf("%d", &num);
for (int j = 1; j <= num; j++)
{
scanf("%d", &x);
a[i][x] = 1;
}
}
printf("%s\n", maxMatch() == p ? "YES" : "NO");
}
return 0;
}