Cod sursa(job #3357869)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 18:41:43
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

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] && capacitate[node][vecin] - flux[node][vecin] > 0) {
                q.push(vecin);
                vis[vecin] = 1;
                p[vecin] = node;
            }
        }
    }
    if (!vis[d]) {
        return 0;
    }
    int mn = 1e9;
    int node = d;
    while (node != s) {
        mn = min(mn, capacitate[p[node]][node] - flux[p[node]][node]);
        node = p[node];
    }
    node = d;
    while (node != s) {
        flux[p[node]][node] += mn;
        flux[node][p[node]] -= mn;
        node = p[node];
    }
    return mn;

}

int main() {
    ifstream fin("maxflow.in");
    ofstream fout("maxflow.out");
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> 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 == 0) {
            break;
        }
        maxFlow += flow;
    }
    fout << maxFlow;
    return 0;
}