标签:
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4500 Accepted Submission(s): 1938
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cstdlib> #include<cmath> #include<algorithm> #include<queue> #include<vector> #include<stack> using namespace std; #define INF 1<<30 int n,nx,ny; int link[310],lx[310],ly[310],slack[310],w[310][310],visx[310],visy[310]; bool dfs(int x) { visx[x]=1; for(int y=1;y<=ny;y++) { if(visy[y]) continue; int t=lx[x]+ly[y]-w[x][y]; if(t==0) { visy[y]=1; if(link[y]==-1||dfs(link[y])) { link[y]=x; return 1; } } else if(slack[y]>t) slack[y]=t; } return 0; } int km() { memset(link,-1,sizeof(link)); memset(ly,0,sizeof(ly)); for(int i=1;i<=nx;i++) { lx[i]=-INF; for(int j=1;j<=ny;j++) lx[i]=max(lx[i],w[i][j]); } for(int x=1;x<=nx;x++) { for(int i=1;i<=ny;i++) slack[i]=INF; while(1) { memset(visx,0,sizeof(visx)); memset(visy,0,sizeof(visy)); if(dfs(x)) break; int d=INF; for(int i=1;i<=ny;i++) { if(!visy[i]&&d>slack[i]) d=slack[i]; } for(int i=1;i<=nx;i++) { if(visx[i]) lx[i]-=d; } for(int i=1;i<=ny;i++) { if(visy[i]) ly[i]+=d; else slack[i]-=d; } } } int res=0; for(int i=1;i<=ny;i++) if(link[i]!=-1) res+=w[link[i]][i]; return res; } int main() { while(scanf("%d",&n)!=EOF) { nx=ny=n; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) scanf("%d",&w[i][j]); } int ans=km(); printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/a972290869/p/4350683.html