1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 using namespace std; 6 const int N = 110; 7 int edge[N][N], match[N], vis[N], fa[N]; 8 int n, m, f, t; 9 int find(int x) { 10 return fa[x] = (fa[x]==x ? x: find(fa[x])); 11 } 12 bool dfs(int u) { 13 for(int v = 1; v <= n; v ++) { 14 if(edge[u][v] && !vis[v]) { 15 vis[v] = 1; 16 if(match[v] == -1 || dfs(match[v])){ 17 match[v] = u; 18 return true; 19 } 20 } 21 } 22 return false; 23 } 24 int main() { 25 ios::sync_with_stdio(false); 26 cin>>t; 27 while(t--) { 28 cin>>n>>m>>f; 29 for(int i = 1; i <= n; i ++) fa[i] = i; 30 memset(edge, 0, sizeof(edge)); 31 int u, v; 32 for(int i = 1; i <= m; i ++) { 33 cin>>u>>v; 34 edge[u][v] = 1; 35 } 36 for(int i = 1; i <= f; i ++) { 37 cin>>u>>v; 38 fa[find(u)] = find(v); 39 } 40 for(int i = 1; i <= n; i ++) { 41 for(int j = 1; j <= n; j ++) { 42 if(find(i)==find(j)) { 43 for(int k = 1; k <= n; k ++) { 44 if(edge[i][k])edge[j][k] = 1; 45 } 46 } 47 } 48 } 49 int ans = 0; 50 while(1) { 51 int res = 0; 52 memset(match, -1, sizeof(match)); 53 for(int i = 1; i <= n; i ++) { 54 memset(vis, 0, sizeof(vis)); 55 if(dfs(i)) res++; 56 } 57 if(res < n) break; 58 ans++; 59 for(int i = 1; i <= n; i ++) { 60 if(match[i] != -1) { 61 edge[match[i]][i] = 0; 62 } 63 } 64 // for(int i = 1; i <= n; i ++) { 65 // for(int j = 1; j <= n; j ++) printf("%d ", edge[i][j]); 66 // printf("\n"); 67 // } 68 } 69 printf("%d\n",ans); 70 } 71 return 0; 72 }
HDU 3081 Marriage Match II 二分图最大匹配
原文:http://www.cnblogs.com/xingkongyihao/p/7273770.html