标签:others view sum class search title accept lan color
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2255
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11022 Accepted Submission(s): 4877
题解:
二分图最大权匹配的模板题。模板来自kuangbin,在此特别鸣谢!
KM算法详解:http://www.cnblogs.com/wenruo/p/5264235.html
代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int INF = 2e9; 5 const LL LNF = 9e18; 6 const int mod = 1e9+7; 7 const int MAXN = 300+10; 8 9 int nx, ny; 10 int g[MAXN][MAXN]; 11 int linker[MAXN], lx[MAXN], ly[MAXN]; 12 int slack[MAXN]; 13 bool visx[MAXN], visy[MAXN]; 14 15 bool DFS(int x) 16 { 17 visx[x] = true; 18 for(int y = 0; y<ny; y++) 19 { 20 if(visy[y]) continue; 21 int tmp = lx[x] + ly[y] - g[x][y]; 22 if(tmp==0) 23 { 24 visy[y] = true; 25 if(linker[y]==-1 || DFS(linker[y])) 26 { 27 linker[y] = x; 28 return true; 29 } 30 } 31 else 32 slack[y] = min(slack[y], tmp); 33 } 34 return false; 35 } 36 37 int KM() 38 { 39 memset(linker, -1, sizeof(linker)); 40 memset(ly, 0, sizeof(ly)); 41 for(int i = 0; i<nx; i++) 42 { 43 lx[i] = -INF; 44 for(int j = 0; j<ny; j++) 45 lx[i] = max(lx[i], g[i][j]); 46 } 47 48 for(int x = 0; x<nx; x++) 49 { 50 for(int i = 0; i<ny; i++) 51 slack[i] = INF; 52 while(true) 53 { 54 memset(visx, 0, sizeof(visx)); 55 memset(visy, 0, sizeof(visy)); 56 57 if(DFS(x)) break; 58 int d = INF; 59 for(int i = 0; i<ny; i++) 60 if(!visy[i]) 61 d = min(d, slack[i]); 62 63 for(int i = 0; i<nx; i++) 64 if(visx[i]) 65 lx[i] -= d; 66 for(int i = 0; i<ny; i++) 67 { 68 if(visy[i]) ly[i] += d; 69 else slack[i] -= d; 70 } 71 } 72 } 73 74 int res = 0; 75 for(int i = 0; i<ny; i++) 76 if(linker[i]!=-1) 77 res += g[linker[i]][i]; 78 return res; 79 } 80 81 int main() 82 { 83 int n; 84 while(scanf("%d",&n)!=EOF) 85 { 86 nx = ny = n; 87 for(int i = 0; i<nx; i++) 88 for(int j = 0; j<ny; j++) 89 scanf("%d",&g[i][j]); 90 printf("%d\n", KM()); 91 } 92 }
标签:others view sum class search title accept lan color
原文地址:http://www.cnblogs.com/DOLFAMINGO/p/7538606.html