Students go to the roller coaster, but to do the roller coaster, they must be a male student and a female student,
Now I want to tell you how many students can ride on a roller coaster with each other.
Both men and women <= 500
Ideas:
Connect a female student with a favorite male student, and then find the maximum matching of the Bipartite Graph.
You can also use the largest stream to create an edge with a capacity of 1 between the source site and the female students, and create an edge with a capacity of 1 for both the female students and their favorite male students, finally, we will establish a Jike with a capacity of 1 between the male and the sink, and find the maximum Liu.
The Hungary algorithm, which is stored directly by the number of people using the adjacent matrix.
Code:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 505; 7 bool G[maxn][maxn]; 8 int Left[maxn]; 9 bool vis[maxn];10 int n, m;11 12 bool Find(int u) {13 for(int i = 1; i <= m; i++) {14 if(G[u][i] && !vis[i]) {15 vis[i] = true;16 if(Left[i] == -1 || Find(Left[i])) {17 Left[i] = u;18 return true;19 }20 }21 }22 return false;23 }24 25 void solve() {26 int num = 0;27 memset(Left, -1, sizeof(Left));28 for(int i = 1; i <= n; i++) {29 memset(vis, 0, sizeof(vis));30 if(Find(i)) num++;31 }32 printf("%d\n",num);33 }34 35 int main() {36 int k;37 int u, v;38 // freopen("a.txt","r",stdin);39 while(scanf("%d",&k) && k) {40 scanf("%d %d",&n, &m);41 memset(G, false, sizeof(G));42 for(int i = 0; i < k; i++) {43 scanf("%d %d",&u, &v);44 G[u][v] = 1;45 }46 solve();47 }48 return 0;49 }View code