HDU-1083-Courses(二分图最大匹配【匈牙利算法】
解释:
p 门课程 n个人不同选
问能否一一对应上
典型二分图最大匹配!
Sample Input
2
3 3
3 1 2 3
2 1 2
1 1
3 3
2 1 3
2 1 3
1 1
Sample Output
YES
NO
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int e[305][305];
int book[305],match[305];
int t,p,n;
int dfs(int u)
{
for(int i=1; i<=n; i++)
{
if(!book[i]&&e[u][i])
{
book[i]=1;
if(match[i]==0||dfs(match[i]))
{
match[i]=u;
return 1;
}
}
}
return 0;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&p,&n);
memset(e,0,sizeof(e));
memset(match,0,sizeof(match));
memset(book,0,sizeof(book));
int num,x;
for(int i=1; i<=p; i++)
{
scanf("%d",&num);
for(int j=1; j<=num; j++)
{
scanf("%d",&x);
e[i][x]=1;
}
}
int sum=0;
for(int i=1; i<=p; i++)
{
memset(book,0,sizeof(book));
if(dfs(i))
sum++;
}
if(sum==p)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}