Drainage Ditches
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 12079 Accepted Submission(s): 5718
Farmer John knows not only how many gallons of water each ditch can transport per minute but also the exact layout of the ditches, which feed out of the pond and into each other and stream in a potentially complex network.
Given all this information, determine the maximum rate at which water can be transported out of the pond and into the stream. For any given ditch, water flows in only one direction, but there might be a way that water can flow in a circle.
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
50
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define INF 99999999
using namespace std;
int n,m;
struct ArcType{
int c,f;
}edge[222][222];
int Prev[222];
int alpha[222];
int flag[222];
int qu[222];
int v,qs,qe;
void ford(){
int i,j;
while(1){
for(i=0;i<222;i++)
flag[i]=Prev[i]=alpha[i]=-1;
//memset(flag,0xff,sizeof(flag));
//memset(Prev,0xff,sizeof(Prev));
//memset(alpha,0xff,sizeof(alpha));
flag[1]=0;Prev[1]=0;alpha[1]=INF;
qs=qe=0;
qu[qe]=1;qe++;
while(qs<qe&&flag[m]==-1){
v=qu[qs];qs++;
for(i=1;i<=m;i++){
if(flag[i]==-1){
if(edge[v][i].c<INF&&edge[v][i].f<edge[v][i].c){
flag[i]=0;Prev[i]=v;
alpha[i]=min(alpha[v],edge[v][i].c-edge[v][i].f);
qu[qe]=i;qe++;
}
else if(edge[i][v].c<INF&&edge[i][v].f>0){
flag[i]=0;Prev[i]=-v;
alpha[i]=min(alpha[v],edge[i][v].f);
qu[qe]=i;qe++;
}
}
}
flag[v]=1;
}
if(flag[m]==-1||alpha[m]==0) break;
int k1=m,k2=abs(Prev[k1]);
int a=alpha[m];
while(1){
if(edge[k2][k1].f<INF) edge[k2][k1].f=edge[k2][k1].f+a;
else edge[k1][k2].f=edge[k1][k2].f-a;
if(k2==1) break;
k1=k2;
k2=abs(Prev[k2]);
}
}
int maxflow=0;
for(i=1;i<=m;i++){
for(j=1;j<=m;j++){
if(i==1&&edge[i][j].f<INF) maxflow+=edge[i][j].f;
}
}
printf("%d\n",maxflow);
}
int main(int argc, char *argv[])
{
int u,v,w;
while(scanf("%d%d",&n,&m)!=EOF){
int i,j;
for(i=1;i<=m;i++){
for(j=1;j<=m;j++) edge[i][j].c=edge[i][j].f=INF;
}
for(i=0;i<n;i++){
scanf("%d%d%d",&u,&v,&w);
if(edge[u][v].c<INF) edge[u][v].c+=w;
else {
edge[u][v].c=w;edge[u][v].f=0;
}
}
ford();
}
return 0;
}