hdu1853 km算法
1 //hdu1853 2 #include<stdio.h> 3 #include<string.h> 4 #define INF 99999999 5 int map[103][103],pr[103],pl[103],visr[103],visl[103],slack[103],match[103]; 6 int n,m; 7 int dfs(int u) 8 { 9 int i,j,val; 10 11 visl[u]=1; 12 for(i=1;i<=n;i++) 13 { 14 if(!visr[i]) 15 { 16 val=pr[i]+pl[u]-map[u][i]; 17 if(val==0) 18 { 19 visr[i]=1; 20 if(match[i]==-1||dfs(match[i])) 21 { 22 match[i]=u; 23 return 1; 24 } 25 } 26 if(val>0&&slack[i]>val) 27 slack[i]=val; 28 } 29 } 30 return 0; 31 } 32 void km() 33 { 34 int i,j,res=0,d; 35 for(i=0;i<=n;i++) 36 pl[i]=INF; 37 memset(pr,0,sizeof(pr)); 38 memset(match,-1,sizeof(match)); 39 for(i=1;i<=n;i++) 40 { 41 for(j=1;j<=n;j++) 42 slack[j]=INF; 43 while(1) 44 { 45 memset(visr,0,sizeof(visr)); 46 memset(visl,0,sizeof(visl)); 47 if(dfs(i)) 48 break; 49 d=INF; 50 for(j=1;j<=n;j++) 51 { 52 if(!visr[j]&&d>slack[j]) 53 d=slack[j]; 54 } 55 for(j=1;j<=n;j++) 56 { 57 if(visr[j]) 58 pr[j]+=d; 59 if(visl[j]) 60 pl[j]-=d; 61 } 62 } 63 } 64 } 65 int main() 66 { 67 int i,j; 68 while(scanf("%d%d",&n,&m)!=EOF) 69 { 70 for(i=0;i<=n;i++) 71 for(j=0;j<=n;j++) 72 map[i][j]=-INF; 73 74 for(i=0;i<m;i++) 75 { 76 int x,y,z; 77 scanf("%d%d%d",&x,&y,&z); 78 if(map[x][y]<-z) 79 { 80 map[x][y]=-z; 81 } 82 } 83 /*for(i=1;i<=n;i++) 84 { 85 for(j=1;j<=n;j++) 86 printf("%d ",map[i][j]); 87 printf("\n"); 88 }*/ 89 km(); 90 int flag=1; 91 int res=0; 92 for(i=1;i<=n;i++) 93 { 94 if(map[match[i]][i]==-INF) 95 {flag=0;break;} 96 else res+=map[match[i]][i]; 97 } 98 if(!flag)printf("-1\n"); 99 else 100 printf("%d\n",-res); 101 } 102 }