Cod sursa(job #1968162)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 17 aprilie 2017 15:25:37
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

const int nmax = 1005, f_mare = 2000000005;
bool viz[nmax];
int cap[nmax][nmax], fl[nmax][nmax], tt[nmax], x, y, i, j, n, l, m, c, fm, sol;
vector <int> ls[nmax];

bool bfs() {
    queue<int> q;
    for (i = 1; i <= n; i++) viz[i] = 0, tt[i] = -1;
    q.push(1);
    while (q.empty()==0) {
        x = q.front();
        q.pop();
        l = ls[x].size();
        for (i = 0; i < l; i++) {
            y = ls[x][i];
            if (viz[y] == 0 && cap[x][y]-fl[x][y] != 0) {
                viz[y] = 1;
                tt[y] = x;
                q.push(y);
            }
        }
    }
    l = ls[n].size();
    if (viz[n] == 0 || l == 0) return 0;
    for (i = 0; i < l; i++) {
        y = ls[n][i];
        if (cap[y][n] - fl[y][n] == 0) continue;
        tt[x] = y;
        y = n;
        fm = f_mare;
        while (y > 1) {
            x = cap[tt[y]][y] - fl[tt[y]][y];
            if (x == 0) break;
            fm = min(fm, x);
            y = tt[y];
        }
        if (y > 1) continue;
        y = n;
        sol += fm;

        //cout << fm << '\n';
        while (y > 1) {
            fl[tt[y]][y] += fm, fl[y][tt[y]] -= fm;
            y = tt[y];
        }
    }
    return 1;
}

int main() {
    f >> n >> m;
    for (i = 1; i <= m; i++) {
        f >> x >> y >> c;
        ls[x].push_back(y);
        ls[y].push_back(x);
        cap[x][y] = c;
        cap[y][x] = -c;
    }
    while (bfs());
    g << sol;
    return 0;
}