Cod sursa(job #3262966)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 12 decembrie 2024 15:26:14
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;
const int N = 1e3 + 2;

int capacitate[N][N], flux[N][N];
vector<int> G[N];
int n, m;
int vis[N], p[N];

int bfs(int s, int d) {
    queue<int> q;
    q.push(s);
    for (int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[i] = 0;
    }
    vis[s] = 1;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (auto vecin : G[node]) {
            if (!vis[vecin]) {
                if (capacitate[node][vecin] - flux[node][vecin] > 0) {
                    q.push(vecin);
                    vis[vecin] = 1;
                    p[vecin] = node;
                }
            }
        }
    }
    if (!vis[d]) {
        return -1;
    }
    int mn = 1e9;
    vector<int> path;
    while (d != 0) {
        path.push_back(d);
        if (p[d] != 0) {
            mn = min(mn, capacitate[p[d]][d] - flux[p[d]][d]);
        }
        d = p[d];
    }
    reverse(path.begin(), path.end());
    for (int i = 0; i < path.size() - 1; i++) {
        flux[path[i]][path[i + 1]] += mn;
        flux[path[i + 1]][path[i]] -= mn;
    }
    return mn;

}

int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        capacitate[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    int maxFlow = 0;
    while (true) {
        int flow = bfs(1, n);
        if (flow == -1) {
            break;
        }
        maxFlow += flow;
    }
    cout << maxFlow;
    return 0;
}