Cod sursa(job #1165613)

Utilizator SmarandaMaria Pandele Smaranda Data 2 aprilie 2014 19:38:27
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int N = 1001;
const int inf = (1ll << 31) - 1;

int n, m;
int capacity [N][N], flow [N][N], father [N];
vector <int> graph [N];
bool used [N];
queue <int> q;

void bfs (const int &s, const int &d) {
    int node;
    vector <int> :: iterator it;
    memset (used, 0, sizeof (used));
    memset (father, 0, sizeof (father));
    q.push (s);
    used [s] = 1;
    while (!q.empty ()) {
        node = q.front ();
        q.pop ();
        for (it = graph [node].begin (); it != graph [node].end (); ++ it)
            if (*it != d && !used [*it] && capacity [node][*it] - flow [node][*it] > 0) {
                father [*it] = node;
                used [*it] = 1;
                q.push (*it);
            }
    }
}

int maxFlow (const int &s, const int &d) {
    int i, ans = 0, minim, node;
    bool flag;
    vector <int> :: iterator it;
    flag = 1;
    while (flag) {
        bfs (s, d);
        flag = 0;
        for (it = graph [d].begin (); it != graph [d].end (); ++ it) {
            node = *it;
            if (flow [node][d] == capacity [node][d])
                continue;
            if (!used [node])
                continue;
            father [d] = node;
            if (capacity [node][d] - flow [node][d] > 0)
                flag = 1;
            minim = inf;
            for (i = d; i != s; i = father [i])
                if (minim > capacity [father [i]][i] - flow [father [i]][i])
                    minim = capacity [father [i]][i] - flow [father [i]][i];
            if (minim == 0)
                continue;
            for (i = d; i != s; i = father [i]) {
                flow [father [i]][i] += minim;
                flow [i][father [i]] -= minim;
            }
            ans += minim;
        }
    }
    return ans;
}

int main () {
    int i, x, y, c;

    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, &c);
        graph [x].push_back (y);
        graph [y].push_back (x);
        capacity [x][y] = c;
    }
    printf ("%d", maxFlow (1, n));
    return 0;
}