forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1140Courses.cpp
More file actions
62 lines (56 loc) · 1.29 KB
/
1140Courses.cpp
File metadata and controls
62 lines (56 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* ZOJ 1140 Courses
*
* 00:00.73 964k
*/
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
//二分图完备匹配,hungary算法,邻接阵形式,复杂度O(m*m*n)
//返回是否是完备匹配,传入二分图大小m,n和邻接阵mat,非零元素表示有边
//如存在,match1,match2返回一个完备匹配,未匹配顶点match值为-1,否则无意义
#define MAXN 300
#define _clr(x) memset(x,0xff,sizeof(int)*MAXN)
int hungary(int m,int n,int mat[][MAXN],int* match1,int* match2){
int s[MAXN],t[MAXN],p,q,ret=0,i,j,k;
if (m>n) return 0;
for (_clr(match1),_clr(match2),i=0;i<m&&ret==i;ret+=(match1[i++]>=0))
for (_clr(t),s[p=q=0]=i;p<=q&&match1[i]<0;p++)
for (k=s[p],j=0;j<n&&match1[i]<0;j++)
if (mat[k][j]&&t[j]<0){
s[++q]=match2[j],t[j]=k;
if (s[q]<0)
for (p=j;p>=0;j=p)
match2[j]=k=t[j],p=match1[k],match1[k]=j;
}
return ret==m;
}
int match1[MAXN], match2[MAXN];
int m, n;
int mat[100][300];
int Run() {
scanf("%d %d", &m, &n);
memset(mat, 0, sizeof(mat));
for (int i = 0; i < m; ++i) {
int num, tmp;
scanf("%d", &num);
for (int j = 0; j < num; ++j) {
scanf("%d", &tmp);
--tmp;
mat[i][tmp] = 1;
}
}
if (hungary(m, n, mat, match1, match2))
printf("YES\n");
else
printf("NO\n");
return 0;
}
int main() {
int kase;
for (scanf("%d", &kase); kase; --kase) {
Run();
}
return 0;
}