Uva1349optimal Bus Route Design

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.