Cod sursa(job #1635701)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 6 martie 2016 19:43:37
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("maxflow.in");
ofstream os("maxflow.out");

using VI = vector<int>;
using VVI = vector<VI>;
using VP = vector<pair<int, int>>;
using VVP = vector<VP>;
using VPP = vector<pair<int, pair<int, int>>>;

int n, m, answ, flow;
VI t;
VVI g, c;
queue<int> q;

void Read();
bool Flow();

int main()
{
    Read();
    while ( Flow() )
        for ( const auto &nod : g[n] )
        {
            if ( nod != 1 && ( !t[nod] || c[nod][n] <= 0 ) )
                continue;
            t[n] = nod;
            flow = INF;
            for ( int x = n; t[x]; x = t[x] )
                flow = min(flow, c[t[x]][x]);
            if ( flow == INF )
                continue;
            for ( int x = n; t[x]; x = t[x] )
            {
                c[t[x]][x] -= flow;
                c[x][t[x]] += flow;
            }
            answ += flow;
        }
    os << answ;
    is.close();
    os.close();
    return 0;
}

bool Flow()
{
    t = VI(n + 1, 0);
    q.push(1);
    int nod;
    while ( q.size() )
    {
        nod = q.front();
        q.pop();
        if ( nod == n )
            continue;
        for ( const auto &nodv : g[nod] )
        {
            if ( nodv != 1 && !t[nodv] && c[nod][nodv] > 0 )
            {
                t[nodv] = nod;
                q.push(nodv);
            }
        }
    }
    if ( t[n] )
        return true;
    return false;
}

void Read()
{
    is >> n >> m;
    g = VVI(n + 1);
    c = VVI(n + 1, VI(n + 1));
    int x, y;
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
        is >> c[x][y];
    }
}