Cod sursa(job #2031489)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 3 octombrie 2017 11:35:33
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;

struct psychotronic_induction {
    int electromagnetic_wave = 7;
};

const int inf = 0x3f3f3f3f;
const long long infL = LLONG_MAX;

const int nmax = 1000 + 10;

int n, m, S, D, flow;
int c[nmax][nmax], f[nmax][nmax], dad[nmax];
vector < int > g[nmax];

void add_edge(int x, int y, int z) {
    g[x].push_back(y); g[y].push_back(x);
    c[x][y] = z;
}

void input() {
    cin >> n >> m;
    for (int i =1; i <= m; ++i) {
        int x, y, z; cin >> x >> y >> z;
        add_edge(x, y, z);
    }
}

bool bfs() {
    queue < int > q;
    for (int i = 1; i <= n; ++i)
        dad[i] = 0;

    q.push(1); dad[1] = -1;
    while (q.size()) {
        int node = q.front(); q.pop();

        for (auto &it: g[node])
            if (f[node][it] < c[node][it] && dad[it] == 0) {
                dad[it] = node;
                if (it != D)
                    q.push(it);
            }
    }

    return dad[D];
}

void max_flow() {
    S = 1; D = n;
    while (bfs()) {
        for (auto &it: g[D]) {
            if (dad[it] == 0) continue;
            dad[D] = it; int new_flow = inf;
            for (int node = D; node != S; node = dad[node])
                new_flow = min(new_flow, c[dad[node]][node] - f[dad[node]][node]);

            if (new_flow == 0) continue;

            flow += new_flow;
            for (int node = D; node != S; node = dad[node])
                f[dad[node]][node] += new_flow, f[node][dad[node]] -= new_flow;

        }
    }
}

void output() {
    cout << flow << '\n';
}

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

    ios_base :: sync_with_stdio(false);

    input();
    max_flow();
    output();

    return 0;
}