Cod sursa(job #3357811)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 15:10:32
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <vector>
#include <queue>
#include <fstream>
using namespace std;

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

const int N = 1010;
int cap[N][N];
int flow[N][N];
vector<int> gr[N];
int dad[N];
int n, m;

int bfs() {
    for (int i = 1; i <= n; i++) dad[i] = 0;
    queue<int> q;
    q.push(1);
    dad[1] = 1;
    while (!q.empty()) {
        int now = q.front(); q.pop();
        for (int x : gr[now]) {
            if (!dad[x] && flow[now][x] < cap[now][x]) {
                dad[x] = now;
                if (x == n) return 1;
                q.push(x);
            }
        }
    }
    return 0;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        gr[a].push_back(b);
        gr[b].push_back(a);
        cap[a][b] += c;
    }

    int ans = 0;
    while (bfs()) {
        int MIN = 1e9;
        int now = n;
        while (now != 1) {
            MIN = min(MIN, cap[dad[now]][now] - flow[dad[now]][now]);
            now = dad[now];
        }
        now = n;
        while (now != 1) {
            flow[dad[now]][now] += MIN;
            flow[now][dad[now]] -= MIN;
            now = dad[now];
        }
        ans += MIN;
    }

    cout << ans;
    return 0;
}