POJ-1469 COURSES---Bipartite Graph Maximum Matching--Hungarian Algorithm

Topic link:

https://vjudge.net/problem/POJ-1469

Topic meaning:

Given p courses and n students, a student can choose 0, 1, or multiple courses, and now requires a set of p students that meets the following 2 conditions:

1. Each student chooses a different course

2. Each course has a different representation

If satisfied, output YES

Problem solving ideas:

Bipartite graph maximum matching.

The adjacency matrix map[i][j] indicates that student j likes course i, and then finds and matches the course. If the match is successful, the student is marked, and then the number of matches can be counted.

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<vector>
 6 #include<queue>
 7 using namespace std;
 8 typedef pair<int, int> Pair ;
 9 typedef long long ll;
10 const int INF = 0x3f3f3f3f;
11 const int maxn = 300 + 10;
12 int T, n, m, cases;
13 vector<int>G[maxn];
14 int cx[maxn], cy[maxn];
15 bool vis[maxn];
16 bool dfs(int u)
17 {
18     for(int i = 0; i < G[u].size(); i++)
19     {
20         int v = G[u][i];
21         if(!vis[v])
22         {
23             vis[v]  =1;//加入增广路
24             if(cy[v] == -1 || dfs(cy[v]))
25             {
26                 cx[u] = v;
27                 cy[v] = u;
28                 return 1;
29             }
30         }
31     }
32     return 0;
33 }
34 int maxmatch()
35 {
36     int ans = 0;
37     memset(cx, -1, sizeof(cx));
38     memset(cy, -1, sizeof(cy));
39     for(int i = 1; i <= n; i++)
40     {
41         if(cx[i] == -1)
42         {
43             memset(vis, 0, sizeof(vis));
44             ans += dfs(i);
45         }
46     }
47     return ans;
48 }
49 int main()
50 {
51     cin >> T;
52     while(T--)
53     {
54         scanf("%d%d", &n, &m);
55         int x, t;
56         for(int i = 1; i <= n; i++)
57         {
58             scanf("%d", &t);
59             G[i].clear();
60             for(int j = 0; j < t; j++)
61             {
62                 scanf("%d", &x);
63                 G[i].push_back(x);
64             }
65         }
66         if(maxmatch() == n)cout<<"YES"<<endl;
67         else cout<<"NO"<<endl;
68     }
69     return 0;
70 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324441126&siteId=291194637