#include #include #include #include #include int N=INT_MAX,N1,N2,TOT=0; char tty; struct E { struct E *next,*forw; struct V *s,*d; int f,c; }; struct V { struct V *path; struct E *e,*back; } *V,**patht; static void get(const char *s,int *vp) { int i; if (tty) { fputs(s,stdout); fputs(": ",stdout); fflush(stdout); } i=scanf("%d",vp); assert(i==1); assert(*vp>=1 && *vp<=N); } int main(void) { int i,V1,V2,C,diff; tty=!!ttyname(STDIN_FILENO); get("Number of cities",&N ); assert(N>=2); get("Starting city #" ,&N1); get("Ending city #" ,&N2); if (tty) puts("Write triples. Finish by EOF"); V=calloc(N+1,sizeof(*V)); assert(V); while ((i=scanf("%d%d%d",&V1,&V2,&C))==3) { struct E *e,*e0,*e1; assert(V1>=1 && V1<=N && V2>=1 && V2<=N && V1!=V2 && C>0); for (e=V[V1].e;e;e=e->next) assert(!(e->forw==e && e->d==V+V2)); e0=malloc(sizeof(*e0)); assert(e0); e1=malloc(sizeof(*e1)); assert(e1); e0->next=V[V1].e; V[V1].e=e0; e1->next=V[V2].e; V[V2].e=e1; e0->s=V+V1; e0->d=V+V2; e1->s=V+V2; e1->d=V+V1; e0->forw=e1->forw=e0; e0->f=0; e0->c=C; e1->f=e1->c=-1; } assert(i<=0); for (;;) { struct V *p,*p2; struct E *e; int d; for (i=1;i<=N;i++) V[i].path=NULL; patht=&V[N1].path; V[N1].back=NULL; for (p=V+N1;p && p!=V+N2;p=p->path) for (e=p->e;e;e=e->next) if (!e->d->path && (( e==e->forw && e->fc ) ||( e!=e->forw && e->forw->f>0 ))) { *patht=e->d; patht=&e->d->path; e->d->back=e; } if (!p) break; diff=INT_MAX; for (p2=p;(e=p->back);p=e->s) { d=(e==e->forw ? e->c-e->f : e->f); assert(d>0); if (d0 || diffback);p=e->s) if (e==e->forw) e->f+=diff; else e->f-=diff; if (p2->back->forw==p2->back) TOT+=diff; else TOT-=diff; assert(TOT>0); } printf("Total network flow is: %d\n",TOT); return(EXIT_SUCCESS); }