The minimum weights of the binary graphs are perfectly matched.
A minimum charge flow can run, remember to check, whether the capacity is full, if not run full, it means there is no perfect match.
#include <cstdio>#include<algorithm>#include<cstring>using namespacestd;Const intMAXN = -+Ten;Const intMAXM =50000+Ten;Const intINF =0x3f3f3f3f;intG[maxn],v[maxm],f[maxm],c[maxm],nex[maxm],eid;intid[maxn][2],vid;intn,ans,s,t;BOOLINQUE[MAXN];intQ[MAXM],DIST[MAXN],PRE[MAXN];voidAddedge (intAintBintFintC) {V[eid]=b; F[eid]=f; C[eid]=c; Nex[eid]=g[a]; g[a]=eid++; V[eid]=a; f[eid]=0; C[eid]=-c; NEX[EID]=G[B]; g[b]=eid++; }BOOLbuild () {if(SCANF ("%d", &n) = =1&&N) {memset (g,-1,sizeof(g)); Eid=0; Vid=0; S=++vid; t=++vid; for(intI=1; i<=n;i++) {id[i][0]=++vid; id[i][1]=++vid; Addedge (s,id[i][0],1,0); Addedge (id[i][1],t,1,0); } for(intI=1, j,d;i<=n;i++) while(SCANF ("%d", &j) &&j) {scanf ("%d",&d); Addedge (id[i][0],id[j][1],1, D); } return true; } return false;}BOOLSPFA () {intU,l,r; L=r=0; memset (Dist,0x3f,sizeof(Dist)); Dist[s]=0; Inque[q[r++]=s]=1; while(l<r) {Inque[u=q[l++]]=0; for(intI=g[u];~i;i=Nex[i])if(F[i] && dist[v[i]]>dist[u]+C[i]) {Dist[v[i]]=dist[u]+C[i]; Pre[v[i]]=i; if(!inque[v[i]]) inque[q[r++]=v[i]]=1; } } returndist[t]<inf;}intaugment () {intaug=inf,res=0; for(inti=t;i!=s;i=v[pre[i]^1]) aug=min (Aug,f[pre[i]]); for(inti=t;i!=s;i=v[pre[i]^1]) {F[pre[i]]-=; F[pre[i]^1]+=; Res+=aug*C[pre[i]]; } ans+=; returnRes;}voidsolve () {ans=0; intres=0; while(SPFA ()) res+=augment (); if(ans!=n) printf ("n\n"); Elseprintf"%d\n", RES); }intMain () { while(Build ()) solve (); return 0;}
Uva1349optimal Bus Route Design