Cod sursa(job #1262770)

Utilizator SmarandaMaria Pandele Smaranda Data 13 noiembrie 2014 15:48:29
Problema Flux maxim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 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, const int &ob) {
    vector <int> :: iterator it;
    int x;

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

int main () {
    int n, m, x, y, cc, flow = 0, minflow, i, ob;

    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);
        c [x][y] = cc;
    }

ob = 1;
    while (bfs (1, n, ob)) {
        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 == (1ll << 31) - 1)
            break;
        flow += minflow;
        for (i = n; i > 1; i = last [i]) {
            f [last [i]][i] += minflow;
            f [i][last [i]] -= minflow;
        }
      ++ ob;
    }
    printf ("%d\n", flow);
    return 0;
}