Cod sursa(job #1985436)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 27 mai 2017 21:53:31
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1004;
const int INF = 0x3f3f3f3f;

int n, m;
vector<int> g[NMAX];
int pre[NMAX];
int rez[NMAX][NMAX];
int totalFlow;
int source, drain;


void read() {

    cin >> n >> m;
    source = 1;
    drain = n;

    for(int i = 1; i <= m; ++i) {

        int x, y, z;
        cin >> x >> y >> z;
        g[x].push_back(y);
        g[y].push_back(x);
        rez[x][y] += z;
    }
}

bool bfs(int source, int drain) {

    deque<int> q;
    int viz[NMAX];

    memset(viz, 0, sizeof(viz));

    q.push_back(source);
    viz[source] = 1;
    pre[source] = source;

    while(!q.empty()) {

        int node = q.back();
        q.pop_back();

        if(node == drain) continue;

        for(int x : g[node])
            if(viz[x] == 0 && rez[node][x] > 0) {
                viz[x] = 1;
                pre[x] = node;
                q.push_front(x);
            }
    }


    return viz[drain] == 1;

}

void solve(int source, int drain) {

    while(bfs(source, drain)) {
        for(int x : g[drain]) {

            int flow = rez[x][drain];


            if(flow == 0) continue;

             for(int node = x; node != pre[node]; node = pre[node])
                flow = min(flow, rez[pre[node]][node]);

            if(flow <= 0) continue;

            for(int node = x;  node != pre[node]; node = pre[node]) {
                rez[pre[node]][node] -= flow;
                rez[node][pre[node]] += flow;
            }

            totalFlow += flow;
        }
    }
}
int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    ios::sync_with_stdio(false);

    read();
    solve(source, drain);

    cout << totalFlow << '\n';

    return 0;
}