标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2255
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #include<vector> 8 #include<queue> 9 #define inf 0x7fffffff 10 using namespace std; 11 const int maxn=300+10; 12 13 int n,nx,ny; 14 int lx[maxn],ly[maxn],visx[maxn],visy[maxn]; 15 int link[maxn],slack[maxn]; 16 int w[maxn][maxn]; 17 18 int dfs(int x) 19 { 20 visx[x]=1; 21 for (int y=1 ;y<=ny ;y++) 22 { 23 if (visy[y]) continue; 24 int t=lx[x]+ly[y]-w[x][y]; 25 if (t==0) 26 { 27 visy[y]=1; 28 if (link[y]==-1 || dfs(link[y])) 29 { 30 link[y]=x; 31 return 1; 32 } 33 } 34 else if (slack[y]>t) slack[y]=t; 35 } 36 return 0; 37 } 38 39 int KM() 40 { 41 memset(ly,0,sizeof(ly)); 42 memset(link,-1,sizeof(link)); 43 for (int x=1 ;x<=nx ;x++) 44 { 45 lx[x]=-inf; 46 for (int y=1 ;y<=ny ;y++) 47 lx[x]=max(lx[x],w[x][y]); 48 } 49 for (int x=1 ;x<=nx ;x++) 50 { 51 for (int j=1 ;j<=ny ;j++) slack[j]=inf; 52 while (1) 53 { 54 memset(visx,0,sizeof(visx)); 55 memset(visy,0,sizeof(visy)); 56 if (dfs(x)) break; 57 int d=inf; 58 for (int j=1 ;j<=ny ;j++) 59 { 60 if (!visy[j] && slack[j]<d) 61 d=slack[j]; 62 } 63 for (int i=1 ;i<=nx ;i++) 64 if (visx[i]) lx[i] -= d; 65 for (int i=1 ;i<=ny ;i++) 66 { 67 if (visy[i]) ly[i] += d; 68 else slack[i] -= d; 69 } 70 } 71 } 72 int ans=0; 73 for (int i=1 ;i<=ny ;i++) 74 if (link[i]!=-1) ans += w[link[i] ][i]; 75 return ans; 76 } 77 78 int main() 79 { 80 while (scanf("%d",&n)!=EOF) 81 { 82 nx=ny=n; 83 for (int i=1 ;i<=n ;i++) 84 { 85 for (int j=1 ;j<=n ;j++) 86 scanf("%d",&w[i][j]); 87 } 88 printf("%d\n",KM()); 89 } 90 return 0; 91 }
标签:
原文地址:http://www.cnblogs.com/huangxf/p/4337395.html