Cod sursa(job #1262832)

Utilizator SmarandaMaria Pandele Smaranda Data 13 noiembrie 2014 16:32:47
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

const int N = 1002;

vector <int> graph [N];
int used [N];
int c [N][N], f [N][N], last [N];

bool bfs (const int &s, const int &d) {
    vector <int> :: iterator it;
    int x;
    queue <int> q;

    q.push (s);
    memset (last, 0, sizeof (last));
    memset (used, 0, sizeof (used));
    used [s] = 1;
    while (!q.empty ()) {
        x = q.front ();
        for (it = graph [x].begin (); it != graph [x].end (); ++ it)
            if (*it != d && !used [*it] && c [x][*it] - f [x][*it] > 0) {
                q.push (*it);
                last [*it] = x;
                used [*it] = 1;
            }
        q.pop ();
    }
    return 1;
}

int main () {
    int n, m, x, y, cc, flow = 0, minflow, i, s = 0;
    vector <int> :: iterator it;
    bool ok = 1;

    freopen ("maxflow.in", "r", stdin);
    freopen ("maxflow.out", "w", stdout);

    scanf ("%d%d", &n, &m);
    for (i = 1; i <= m; i ++) {
        scanf ("%d%d%d", &x, &y, &cc);
        graph [x].push_back (y);
        graph [y].push_back (x);
        c [x][y] = cc;
    }

    while (ok) {
        bfs (1, n);
        ok = 0;
        for (it = graph [n].begin (); it != graph [n].end (); ++ it) {
            if (f [*it][n] == c [*it][n])
                continue;
            if (used [*it]) {
                if (c [*it][n] - f [*it][n] > 0)
                    ok = 1;
                last [n] = *it;
                minflow = (1ll << 31) - 1;
                for (i = n; i != 1; i = last [i])
                    minflow = min (minflow, c [last [i]][i] - f [last [i]][i]);
                if (minflow == 0)
                    continue;
                flow += minflow;
                for (i = n; i != 1; i = last [i]) {
                    f [last [i]][i] += minflow;
                    f [i][last [i]] -= minflow;
                }
            }
        }
    }
    printf ("%d\n", flow);
    return 0;
}