Cod sursa(job #558966)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 17 martie 2011 15:31:15
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include<cstdio>
#include<cstring>
#include<cmath>
#define INF 10000001
#define Nmx 1001
#define minn(a,b) (a<b) ? a : b

using namespace std;

int s=1,d,prec[Nmx],viz[Nmx],Q[Nmx*10],nr,n,m,C[Nmx][Nmx];
struct nod
{
    int inf;
    nod *urm;
};
nod *G[Nmx];

void add(int x,int y)
{
    nod *aux=new nod;
    aux->inf = y;
    aux->urm = G[x];
    G[x] = aux;
}

void citire()
{
    int x,y,c;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d%d",&x,&y,&c);
        add(x,y);
        add(y,x);
        C[x][y]=c;
        C[y][x]=0;
    }
}

int bfs()
{
    memset(viz,0,sizeof(viz));
    memset(prec,0,sizeof(prec));
    Q[1]=1;
    nr=1;
    int st=1;
    viz[1]=1;
    while(st<=nr)
    {
        int x=Q[st];
        for(nod *p=G[x];p;p=p->urm)
            if(!viz[p->inf]&&C[x][p->inf]>0)
            {
                viz[p->inf]=1;
                prec[p->inf]=x;
                Q[++nr]=p->inf;
            }
        ++st;
    }
    return prec[d];
}

void solve()
{
    int sol=0,Vmin=INF;
    d=n;
    while(bfs())
        for(nod *p=G[d];p;p=p->urm)
        {
            Vmin=INF;
            prec[d]=p->inf;
            for(int j=d;prec[j];j=prec[j])
                Vmin=minn(Vmin,C[prec[j]][j]);
            if(Vmin)
            {
                for(int j=d;prec[j];j=prec[j])
                {
                    C[prec[j]][j]-=Vmin;
                    C[j][prec[j]]+=Vmin;
                }
                sol+=Vmin;
            }
        }
    printf("%d\n",sol);
}

int main()
{
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);
    citire();
    solve();
    return 0;
}