Cod sursa(job #2475805)

Utilizator gabib97Gabriel Boroghina gabib97 Data 17 octombrie 2019 16:54:56
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define N 1005
using namespace std;

int n, m, cap[N][N], parent[N];
vector<int> G[N];

bool bfs() {
    queue<int> Q;
    Q.push(1);
    while (!Q.empty()) {
        int x = Q.front();
        Q.pop();

        for (int y : G[x])
            if (cap[x][y] > 0 && !parent[y]) {
                parent[y] = x;
                Q.push(y);
            }
    }
    return parent[n] != 0;
}

int main() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");

    cin >> n >> m;
    int x, y, c;
    while (m--) {
        cin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        cap[x][y] = c;
    }

    int flow = 0, w;
    while (bfs()) {
        for (int sinkNeighbor: G[n]) {
            // find bottleneck capacity
            w = cap[sinkNeighbor][n];
            for (int node = sinkNeighbor; node != 1; node = parent[node])
                w = min(w, cap[parent[node]][node]);

            // pump flow through the found path
            flow += w;
            cap[sinkNeighbor][n] -= w;
            cap[n][sinkNeighbor] += w;
            for (int node = sinkNeighbor; node != 1; node = parent[node])
                cap[parent[node]][node] -= w, cap[node][parent[node]] += w;
        }
        memset(parent, 0, sizeof(parent));
    }
    cout << flow;
    return 0;
}