Pagini recente » Borderou de evaluare (job #2138107) | Cod sursa (job #498415)
Cod sursa(job #498415)
#include <stdio.h>
const int maxn=1001,INF=110000001;
struct nod {
int inf,c;
nod *next;
} *A[maxn];
int i,N,M,from[maxn];
void citire()
{
int x,y,z;
scanf("%d %d",&N,&M);
for(i=1;i<=M;i++)
{
scanf("%d %d %d",&x,&y,&z);
nod *q=new nod;
q->inf=y;
q->c=z;
q->next=A[x];
A[x]=q;
q=new nod;
q->inf=x;
q->c=0;
q->next=A[y];
A[y]=q;
}
}
int bfs()
{
int v[maxn],c[maxn],ps,pi,k;
for(i=1;i<=N;i++) { v[i]=0; c[i]=0; from[i]=0;}
c[1]=1; v[1]=1; ps=1; pi=1;
while(true)
{
k=c[ps];
for(nod *x=A[k];x;x=x->next)
if(v[x->inf]==0 && x->c>0)
{
c[++pi]=x->inf;
v[x->inf]=1;
from[x->inf]=k; // from[x] = nodul din care se ajunge la x
if(x->inf==N) return 1;
}
ps++;
if(ps>pi) return 0;
}
}
int path()
{
int p,k=N,min=INF; nod *q;
do
{
p=k; k=from[k];
for(q=A[k];q->inf!=p;q=q->next);
if(q->c<min) min=q->c;
}
while(k!=1);
return min;
}
void update(int x)
{
int p,k=N;
do
{
nod *q;
for(q=A[k];q->inf!=from[k];q=q->next);
q->c+=x;
p=k; k=from[k];
for(q=A[k];q->inf!=p;q=q->next);
q->c-=x;
}
while(k!=1);
}
int maxflow()
{
int drum,R=0;
while(bfs()) //pana cand exista drum de la 1 la N
{
drum=path(); //aflu cu cat pot mari fluxul
update(drum); //fac update in graful rezidual
R+=drum; //adaug la rezultat
}
return R;
}
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
citire();
printf("%d",maxflow());
}