题目链接:http://poj.org/problem?id=1469
题目意思:有 N 个人,P个课程,每一个课程有一些学生参加(0个、1个或多个参加)。问 能否使得 P 个课程 恰好与 P 个学生相匹配。
受之前第一道匹配题(POJ 1274 The Perfect Stall)的影响,没有仔细体会是从哪个点匹配到哪个点,这将导致Hungary() 和 dfs() 中 for 循环的约束条件,究竟是遍历课程数 P 还是 学生数N,不要搞混!其实从存储的map[i][j] 可以 知道 怎样遍历的啦 ^_^
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 300 + 5; 7 bool vis[maxn]; 8 int map[maxn][maxn], match[maxn]; 9 int N, P, cnt; 10 11 int dfs(int x) 12 { 13 for (int i = 1; i <= N; i++) // 为p个课程找匹配,N个学生是候选人 14 { 15 if (!vis[i] && map[x][i]) 16 { 17 vis[i] = 1; 18 if (!match[i] || dfs(match[i])) 19 { 20 match[i] = x; 21 // printf("match[%d] = %d ", i, match[i]); 22 return 1; 23 } 24 } 25 } 26 return 0; 27 } 28 29 void Hungary() 30 { 31 cnt = 0; 32 for (int i = 1; i <= P; i++) // 不是N,要区分清楚!! 33 { 34 memset(vis, 0, sizeof(vis)); 35 cnt += dfs(i); 36 } 37 } 38 39 int main() 40 { 41 int T, stu_num, stu_id; 42 while (scanf("%d", &T) != EOF) 43 { 44 while (T--) 45 { 46 memset(match, 0, sizeof(match)); 47 memset(map, 0, sizeof(map)); 48 49 scanf("%d%d", &P, &N); 50 for (int i = 1; i <= P; i++) 51 { 52 scanf("%d", &stu_num); 53 for (int j = 0; j < stu_num; j++) 54 { 55 scanf("%d", &stu_id); 56 map[i][stu_id] = 1; 57 } 58 } 59 Hungary(); 60 printf("%s ", cnt == P ? "YES" : "NO"); 61 } 62 } 63 return 0; 64 }