Cod sursa(job #1988710)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 4 iunie 2017 13:43:10
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;

#define file "maxflow"

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

int n, m, maxFlow;
VI t;
VVI g, c;

void read()
{
    int x, y;
    ifstream is(file".in", ios::in);

    is >> n >> m;
    g = VVI(n + 1);
    c = VVI(n + 1, VI(n + 1));

    for (int i = 1; i <= m; ++i)
    {
        is >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
        is >> c[x][y];
    }
    is.close();
}

bool find_flow()
{
    int x;
    queue<int> q;
    t = VI(n + 1);
    q.push(1);

    while (!q.empty())
    {
        x = q.front();
        q.pop();
        if (x == n)
            continue;
        for (const auto& y : g[x])
            if (y != 1 && !t[y] && c[x][y] > 0)
            {
                    t[y] = x;
                    q.push(y);
            }
    }

    if (t[n])
        return true;
    return false;
}

void solve()
{
    int flow;
    while (find_flow())
        for (const auto& x: g[n])
        {
            if (c[x][n] <= 0 || !t[x])
                continue;
            t[n] = x;
            flow = INF;
            for (int y = n; t[y]; y = t[y])
                flow = min(flow, c[t[y]][y]);
            if (flow == INF)
                continue;
            for (int y = n; t[y]; y = t[y])
            {
                c[t[y]][y] -= flow;
                c[y][t[y]] += flow;
            }
            maxFlow += flow;
        }
}

void write()
{
    ofstream os(file".out", ios::out | ios::trunc);
    os << maxFlow;
    os.close();
}

int main()
{
    read();
    solve();
    write();
    return 0;
}