P6577 【模板】二分图最大权完美匹配 KM算法模板
.
1 #include<bits/stdc++.h> 2 using namespace std; 3 //Data 4 typedef long long ll; 5 const int N=500; 6 const int inf=0x3f3f3f3f; 7 int n,m,e[N+7][N+7]; 8 9 //KM 10 int mb[N+7],vb[N+7],ka[N+7],kb[N+7],p[N+7],c[N+7]; 11 int qf,qb,q[N+7]; 12 void Bfs(int u){ 13 int a,v=0,vl=0,d; 14 for(int i=1;i<=n;i++) p[i]=0,c[i]=inf; 15 mb[v]=u; 16 do { 17 a=mb[v],d=inf,vb[v]=1; 18 for(int b=1;b<=n;b++)if(!vb[b]){ 19 if(c[b]>ka[a]+kb[b]-e[a][b]) 20 c[b]=ka[a]+kb[b]-e[a][b],p[b]=v; 21 if(c[b]<d) d=c[b],vl=b; 22 } 23 for(int b=0;b<=n;b++) 24 if(vb[b]) ka[mb[b]]-=d,kb[b]+=d; 25 else c[b]-=d; 26 v=vl; 27 } while(mb[v]); 28 while(v) mb[v]=mb[p[v]],v=p[v]; 29 } 30 ll KM() 31 { 32 for(int i=1;i<=n;i++) 33 mb[i]=ka[i]=kb[i]=0; 34 for(int a=1;a<=n;a++){ 35 for(int b=1;b<=n;b++) vb[b]=0; 36 Bfs(a); 37 } 38 ll res=0; 39 for(int b=1;b<=n;b++) res+=e[mb[b]][b]; 40 return res; 41 } 42 43 //Main 44 int main(){ 45 scanf("%d%d",&n,&m); 46 for(int a=1;a<=n;a++) 47 for(int b=1;b<=n;b++) e[a][b]=-inf; 48 for(int i=1;i<=m;i++){ 49 int u,v,w; 50 scanf("%d%d%d",&u,&v,&w); 51 e[u][v]=max(e[u][v],w); 52 } 53 printf("%lld\n",KM()); 54 for(int u=1;u<=n;u++) 55 printf("%d ",mb[u]);puts(""); 56 return 0; 57 }