Cod sursa(job #574094)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 6 aprilie 2011 20:15:45
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<cstdio>
#include<cstring>
#include<cmath>
#define INF 10000001
#define Nmx 301
#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;
    }
}

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];
        if(x!=d)
            {
            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 viz[d];
}

void solve()
{
    int sol=0,Vmin=INF;
    d=n;
    while(bfs())
    for(nod *p=G[d];p;p=p->urm)
        if(C[p->inf][d]>0&&viz[p->inf])
        {
            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;
}