二分图匹配(匈牙利算法模板)
最大匹配——匈牙利算法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /**************************************************** 2 二分图匹配(匈牙利算法的DFS实现) 3 INIT:g[][]两边定点划分的情况 4 CALL:res=hungary();输出最大匹配数 5 优点:适于稠密图,DFS找增广路快,实现简洁易于理解 6 时间复杂度:O(VE); 7 ****************************************************/ 8 #include <iostream> 9 #include <cstdio> 10 #include <cstring> 11 using namespace std; 12 const int MAXN=1000; 13 int uN, vN; //u,v数目 14 int g[MAXN][MAXN];//编号是0~n-1的 15 int match[MAXN]; 16 int f[MAXN]; 17 18 bool dfs(int u) 19 { 20 for (int i = 0; i < vN; i++) 21 if (g[u][i] && !f[i]) 22 { 23 f[i] = 1; 24 if (match[i] == -1 || dfs(match[i])) 25 { 26 match[i] = u; 27 return true; 28 } 29 } 30 return false; 31 } 32 33 int hungary() 34 { 35 int ans = 0; 36 memset(match, -1, sizeof(match)); 37 for (int i = 0; i < uN; i++) 38 { 39 memset(f, 0, sizeof(f)); 40 if (dfs(i)) 41 ans++; 42 } 43 return ans; 44 }
相关的题有
HDU 1045
HDU 2063过山车
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 using namespace std; 6 7 #define N 505 8 9 int map[N][N], flag[N]; 10 int pre[N]; 11 int n, m, num; 12 13 int dfs(int cur) 14 { 15 for (int i = 1; i <= m ;i++) 16 { 17 if (map[cur][i] && !flag[i]) 18 { 19 flag[i] = 1; 20 if (pre[i] == -1 || dfs(pre[i])) 21 { 22 pre[i] = cur; 23 return 1; 24 } 25 } 26 } 27 return 0; 28 } 29 30 int main() 31 { 32 int girl, boy, sum; 33 while (cin >> num && num) 34 { 35 cin >> n >> m; 36 memset(map, 0, sizeof(map)); 37 memset(pre, -1, sizeof(pre)); 38 for (int i = 0; i < num; i++) 39 { 40 cin >> girl >> boy; 41 map[girl][boy] = 1; 42 } 43 sum = 0; 44 for (int i = 1; i <= n; i++) 45 { 46 memset(flag, 0, sizeof(flag)); 47 sum += dfs(i); 48 } 49 cout << sum << endl; 50 } 51 return 0; 52 }