Cod sursa(job #3357983)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:35:39
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;

const int MAXN = 1005;
const int INF = 1e9;

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

int n, m;
int capacity[MAXN][MAXN];
int flow[MAXN][MAXN];
int parent[MAXN];

bool bfs() {
    for (int i = 1; i <= n; i++) parent[i] = -1;
    queue<int> q;
    q.push(1);
    parent[1] = 0;

    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int v = 1; v <= n; v++) {
            if (parent[v] == -1 && v != 1 && capacity[u][v] - flow[u][v] > 0) {
                parent[v] = u;
                q.push(v);
                if (v == n) return true;
            }
        }
    }
    return false;
}

int edmonds_karp() {
    int max_flow = 0;
    while (bfs()) {
        int path_flow = INF;
        for (int v = n; v != 1; v = parent[v]) {
            int u = parent[v];
            path_flow = min(path_flow, capacity[u][v] - flow[u][v]);
        }
        for (int v = n; v != 1; v = parent[v]) {
            int u = parent[v];
            flow[u][v] += path_flow;
            flow[v][u] -= path_flow;
        }
        max_flow += path_flow;
    }
    return max_flow;
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, z;
        fin >> x >> y >> z;
        capacity[x][y] += z;
    }
    fout << edmonds_karp() << '\n';
    fin.close();
    fout.close();
    return 0;
}