Cod sursa(job #1575777)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 21 ianuarie 2016 20:40:05
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#define INF 0x3f3f3f3f
using namespace std;

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

using VI = vector<int>;
using VVI = vector<VI>;

int n, m;
VI t;
VVI g, c;
queue<int> q;
bitset<1001> ok;

void Read();
bool BFS();

int main()
{
    Read();
    int answ = 0, flow;
    t = VI(n + 1);
    while ( BFS() )
        for ( const auto &nod : g[n] )
        {
            if ( !ok[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;
            answ += flow;
            for ( int x = n; t[x]; x = t[x] )
            {
                c[t[x]][x] -= flow;
                c[x][t[x]] += flow;
            }
        }
    os << answ;
    is.close();
    os.close();
    return 0;
}

bool BFS()
{
    ok.reset();
    q.push(1);
    ok[1] = 1;
    int nod;
    while ( !q.empty() )
    {
        nod = q.front();
        q.pop();
        if ( nod == n )
            continue;
        for ( const auto &nodv : g[nod] )
            if ( !ok[nodv] && c[nod][nodv] > 0 )
            {
                q.push(nodv);
                ok[nodv] = 1;
                t[nodv] = nod;
            }
    }
    return ok[n];
}

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