Cod sursa(job #2444166)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 30 iulie 2019 14:30:45
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int N = 1000 + 7;
const int INF = (int) 1e9;
int n, m;
int capacity[N][N];
int parent[N];
vector <int> adj[N];

int bfs(int s, int t) {
    for (int i = 1; i <= n; i++) {
        parent[i] = -1;
    }
    parent[s] = -2;
    queue <pair <int, int>> q;
    q.push({s, INF});

    while (!q.empty()) {
        int cur = q.front().first;
        int flow = q.front().second;
        q.pop();

        for (auto &next : adj[cur]) {
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                int new_flow = min(capacity[cur][next], flow);
                if (next == t) return new_flow;
                q.push({next, new_flow});
            }
        }
    }
    return 0;
}

int max_flow(int s, int t) {
    int flow = 0;
    int new_flow = 0;
    while (new_flow = bfs(s, t)) {
        flow += new_flow;
        int cur = t;
        while (cur != s) {
            int prev = parent[cur];
            capacity[prev][cur] -= new_flow;
            capacity[cur][prev] += new_flow;
            cur = prev;
        }
    }
    return flow;
}

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

    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; i++) {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
        capacity[a][b] = c;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    printf("%d\n", max_flow(1, n));

}