标签:des style blog http java color os strong
6 9 1 2 5 2 3 5 3 1 10 3 4 12 4 1 8 4 6 11 5 4 7 5 6 9 6 5 4 6 5 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1
42 -1HintIn the first sample, there are two cycles, (1->2->3->1) and (6->5->4->6) whose length is 20 + 22 = 42.
这是1853代码,后一题建成双向边就行了,代码类似。
#include"stdio.h" #include"string.h" #define N 105 #define mmax(a,b) ((a)>(b)?(a):(b)) #define mmin(a,b) ((a)<(b)?(a):(b)) const int inf=(int)1e8; int g[N][N],slack[N],n; int link[N],lx[N],ly[N]; int visx[N],visy[N]; int find(int k) { int i; visx[k]=1; for(i=1;i<=n;i++) { if(visy[i]) continue; int d=lx[k]+ly[i]-g[k][i]; if(d==0) { visy[i]=1; if(link[i]==-1||find(link[i])) { link[i]=k; return 1; } } else slack[i]=mmin(slack[i],d); } return 0; } int KM() { int i,j; memset(ly,0,sizeof(ly)); memset(link,-1,sizeof(link)); for(i=1;i<=n;i++) { lx[i]=-inf; for(j=1;j<=n;j++) { lx[i]=mmax(lx[i],g[i][j]); } } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { slack[j]=inf; } while(1) { memset(visx,0,sizeof(visx)); memset(visy,0,sizeof(visy)); if(find(i)) break; else { int d=inf; for(j=1;j<=n;j++) { if(!visy[j]) d=mmin(slack[j],d); } for(j=1;j<=n;j++) { if(visx[j]) lx[j]-=d; if(visy[j]) ly[j]+=d; } } } } int ans=0; for(i=1;i<=n;i++) { if(link[i]==-1||g[link[i]][i]==-inf) break; ans+=g[link[i]][i]; } if(i<=n) return -1; return -ans; } int main() { int i,j,u,v,w,m; while(scanf("%d%d",&n,&m)!=-1) { for(i=1;i<=n;i++) //注意初始化边为最小值 { for(j=1;j<=n;j++) { g[i][j]=-inf; } } while(m--) { scanf("%d%d%d",&u,&v,&w); g[u][v]=mmax(g[u][v],-w); } printf("%d\n",KM()); } return 0; }
hdu 1853 Cyclic Tour && hdu 3435 A new Graph Game(简单KM算法),布布扣,bubuko.com
hdu 1853 Cyclic Tour && hdu 3435 A new Graph Game(简单KM算法)
标签:des style blog http java color os strong
原文地址:http://blog.csdn.net/u011721440/article/details/38227039