Cod sursa(job #1556260)

Utilizator andreiiiiPopa Andrei andreiiii Data 24 decembrie 2015 13:52:32
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <algorithm>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

const int NMAX = 1005;
vector<int> G[NMAX];

int C[NMAX][NMAX], F[NMAX][NMAX];
int father[NMAX];

bool bfs(int s, int d) {
    memset(father, -1, sizeof father);
    father[s] = -2;
    queue<int> q;
    q.push(s);

    while(!q.empty()) {
        int node = q.front();
        q.pop();

        if (node == d) continue;

        for (int p: G[node]) {
            if (father[p] == -1 && C[node][p] > F[node][p]) {
                father[p] = node;
                q.push(p);
            }
        }
    }
    return father[d] != -1;
}

int maxflow(int s, int d) {
    int flow = 0;
    while (bfs(s, d)) {
        for (int p: G[d]) {
            if (father[p] == -1 || C[p][d] == F[p][d]) continue;
            father[d] = p;
            int fmin = 1 << 30;
            for (int i = d; i != s; i = father[i]) {
                fmin = min(fmin, C[father[i]][i] - F[father[i]][i]);
            }
            if (fmin == 0) continue;
            for (int i = d; i != s; i = father[i]) {
                F[father[i]][i] += fmin;
                F[i][father[i]] -= fmin;
            }
            flow += fmin;
        }
    }
    return flow;
}

int main() {
    ifstream fin("maxflow.in");
    ofstream fout("maxflow.out");

    int n, m;
    fin >> n >> m;

    for (int i = 0; i < m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        C[x][y] += c;
        C[y][x] -= c;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    int ans = maxflow(1, n);
    fout << ans << '\n';

    fin.close();
    fout.close();
}