Cod sursa(job #1760825)

Utilizator lianaliana tucar liana Data 21 septembrie 2016 12:24:40
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include<stdio.h>
#include<vector>

using namespace std;

#define inf 510000
#define nmax 1005

vector <int> ma[nmax];
vector <int> ::iterator it;
int cap[nmax][nmax], z, x, m, n, inc, sf, nbfs, co[nmax], viz[nmax], t[nmax], tn[nmax], ntn, nod, fmin, rez, y;

void citire(){
    scanf("%d %d",&n,&m);
    for (int i=1;i<=m;i++){
        scanf("%d %d %d",&x,&y,&z);
        ma[x].push_back(y); cap[x][y]=z;
        ma[y].push_back(x);
    }
}

void bfs(){
    nbfs++; ntn=0;
    inc=sf=co[1]=1;
    viz[1]=nbfs;
    while (inc<=sf){
        x=co[inc++];
        if (x==n)
            break;
        for (it=ma[x].begin();it!=ma[x].end();it++){
            y=*it;
            if (cap[x][y]>0){
                if (viz[y]!=nbfs){
                    co[++sf]=y;
                    viz[y]=nbfs;
                    t[y]=x;
                }
                if (y==n)
                    tn[++ntn]=x;
            }
        }
    }
}

void rezolvare(){
    while (1){
        bfs();
        if(ntn>0){
            for (int i=1;i<=ntn;i++){
                t[n]=tn[i];
                nod=n;  fmin=inf;
                while ((fmin>0)&&(nod>1)){
                    fmin=min(fmin,cap[t[nod]][nod]);
                    nod=t[nod];
                }
                if (fmin>0){
                    nod=n;
                    while (nod>1){
                        cap[t[nod]][nod]-=fmin;
                        cap[nod][t[nod]]+=fmin;
                        nod=t[nod];
                    }
                    rez+=fmin;
                }
            }
        }
        else
            break;
    }
}

int main()
{
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);
    citire();
    rezolvare();
    printf("%d\n",rez);
    return 0;
}