Cod sursa(job #582559)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 15 aprilie 2011 16:18:04
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <cstring>
#include <fstream>
#include <queue>
#define Nmx 1001
#define INF 0x3f3f3f3f

using namespace std;

int s,d,C[Nmx][Nmx],F[Nmx][Nmx],n,prec[Nmx],viz[Nmx],m;
struct nod
{
    int inf;
    nod *urm;
};
nod *G[Nmx];
queue <int> Q;

ifstream fin("maxflow.in");


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

void read()
{
    int x,y,c;
    fin>>n>>m;
    s=1;d=n;
    for(int i=1;i<=m;++i)
    {
        fin>>x>>y>>c;
        add(x,y);
        add(y,x);
        C[x][y]=c;
    }
}

int bellmand()
{
    for(int i=1;i<=n;++i)
        viz[i]=0;
    viz[s]=1;
    prec[s]=0;
    Q.push(s);
    while(!Q.empty())
    {
        int x=Q.front();
        Q.pop();
        if(x!=d)
        {
            for(nod *p=G[x];p;p=p->urm)
                if(C[x][p->inf]-F[x][p->inf]>0&&!viz[p->inf])
                {
                    viz[p->inf]=1;
                    prec[p->inf]=x;
                    Q.push(p->inf);
                }
        }
    }
    return viz[d];
}

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

int main()
{
    freopen("maxflow.out","w",stdout);
    read();
    solve();
    return 0;
}