Cod sursa(job #1165432)

Utilizator tudorv96Tudor Varan tudorv96 Data 2 aprilie 2014 18:07:32
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <queue>
using namespace std;

ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");

const int N = 1005;

int viz[N], f[N][N], c[N][N], n, m, vizit, t[N], sol;
vector <int> g[N];
queue <int> Q;

bool bfs() {
    ++vizit;
    Q.push (1);
    viz[1] = vizit;
    while (Q.size()) {
        int x = Q.front(); Q.pop();
        for (vector <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
            if (f[x][*it] < c[x][*it] && viz[*it] != vizit) {
                t[*it] = x;
                Q.push (*it);
                viz[*it] = vizit;
            }
    }
    return (viz[n] == vizit);
}

int main() {
    fin >> n >> m;
    for (int x, y, cap, i = 0; i < m; ++i) {
        fin >> x >> y >> cap;
        c[x][y] = cap;
        g[x].push_back (y);
        g[y].push_back (x);
    }
    while (bfs())
        for (int i = 1; i < n; ++i)
            if (f[i][n] < c[i][n]) {
                int flux = c[i][n] - f[i][n], x = i;
                while (x != 1) {
                    flux = min (flux, c[t[x]][x] - f[t[x]][x]);
                    x = t[x];
                }
                f[i][n] += flux;
                f[n][i] -= flux;
                x = i;
                while (x != 1) {
                    f[t[x]][x] += flux;
                    f[x][t[x]] -= flux;
                    x = t[x];
                }
                sol += flux;
            }
    fout << sol;
}