Cod sursa(job #3203658)

Utilizator csamoilasamoila ciprian casian csamoila Data 14 februarie 2024 09:42:19
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>
#define NMAX 1001
#define INF 1e9

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n, m;
int capacity[NMAX][NMAX];
vector<vector<int>> adj;

int bfs(int s, int t, vector<int>& parent) {
    fill(parent.begin(), parent.end(), -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 (int next : adj[cur]) {
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                int new_flow = min(flow, capacity[cur][next]);
                if (next == t)
                    return new_flow;
                q.push({next, new_flow});
            }
        }
    }

    return 0;
}

int maxflow(int s, int t) {
    int flow = 0;
    vector<int>parent(n+1);
    int new_flow;

    while (new_flow = bfs(s, t, parent)) {
        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()
{
    fin >> n >> m;
    adj = vector<vector<int>>(n + 1);
    for (int i = 1; i <= m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        capacity[a][b] = c;
        capacity[b][a] = 0;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    fout << maxflow(1, n);
    return 0;
}