Cod sursa(job #879556)

Utilizator SchumiDumitru Andrei Georgian Schumi Data 15 februarie 2013 17:06:50
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <cstring>

#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

#define FORIT(it, v) for (typeof((v).begin()) it = (v).begin(); it != (v).end(); ++it)

const int N = 1005;
const int INF = 0x3f3f3f3f;

int n, m;
int capacitate[N][N];
vector <int> graph[N];

void read() {
    f >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        f >> x >> y >> c;
        graph[x].push_back(y);
        graph[y].push_back(x);
        capacitate[x][y] += c;
    }
}

int solve() {
    queue <int> q;
    int flux[N], father[N];
    bool viz[N];

    memset(viz, false, sizeof(viz));
    memset(flux, 0, sizeof(flux));
    memset(father, 0, sizeof(father));

    flux[1] = INF;
    father[1] = 0;
    q.push(1);
    
    while (!q.empty()) {
        int node = q.front();
        q.pop();

        FORIT(it, graph[node]) {
            if (capacitate[node][*it] > 0 && !viz[*it]) {
                father[*it] = node;
                flux[*it] = min(flux[node], capacitate[node][*it]);
                viz[*it] = true;
                q.push(*it);
            }
        }

        if (viz[n])
            break;
    }
    
    if (flux[n])
    for (int i = n; i != 1; i = father[i]) {
        capacitate[i][father[i]] += flux[n];
        capacitate[father[i]][i] -= flux[n];
    }

    return flux[n];
}

int main() {
    read();
    int ans = 0;
    int add = solve();
    while (add) {
        ans += add;
        add = solve();
    }

    g << ans;
}