Cod sursa(job #1411601)

Utilizator cautionPopescu Teodor caution Data 31 martie 2015 20:26:15
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#define INF 666013
using namespace std;
long n, m, c[1005][1005], flow[1005][1005];
bool *viz;
vector<long> *graf;
long *tree;
bool bf()
{
    queue<long> Q;
    long x, i;
    Q.push(1);
    for(i=1; i<=n; ++i) viz[i]=false;
    tree[1]=1;
    viz[1]=true;
    while(!Q.empty())
    {
        x=Q.front();
        Q.pop();
        for(vector<long>::iterator it=graf[x].begin(), ed=graf[x].end(); it!=ed; ++it)
        {
            if(viz[*it]==false&&c[x][*it]!=flow[x][*it])
            {
                tree[*it]=x;
                Q.push(*it);
                viz[*it]=true;
                if(*it==n) return true;
            }
        }
    }
    return false;
}
int main()
{
    long long sum=0;
    long a, b, aux, i;
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");
    in>>n>>m;
    graf = new vector<long>[n+1];
    tree = new long[n+1];
    viz = new bool[n+1];
    for(i=0; i<m; ++i)
    {
        in>>a>>b>>aux;
        graf[a].push_back(b);
        graf[b].push_back(a);
        c[a][b]=aux;
    }
    while(bf())
    {
        a=n;
        b=INF;
        while(a!=1)
        {
            b=min(b, c[tree[a]][a]-flow[tree[a]][a]);
            a=tree[a];
        }
        sum+=b;
        a=n;
        while(a!=1)
        {
            flow[tree[a]][a]+=b;
            flow[a][tree[a]]-=b;
            a=tree[a];
        }
    }
    out<<sum;
    return 0;
}