Cod sursa(job #3271352)

Utilizator THEO0808Teodor Lepadatu THEO0808 Data 25 ianuarie 2025 19:32:07
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

const int NMAX = 1e3;
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
vector<int> G[NMAX + 1];
int vis[NMAX + 1], p[NMAX + 1];
int n, m;

int bfs(int src, int dest) {
    for(int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[i] = 0;
    }
    queue<int> q;
    q.push(src);
    vis[src] = 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[dest] == 0) {
        return 0;
    }
    int flow = INT_MAX;
    for(int x = dest; x != src; x = p[x]) {
        flow = min(flow, capacitate[p[x]][x] - flux[p[x]][x]);
    }
    for(int x = dest; x != src; x = p[x]) {
        flux[p[x]][x] += flow;
        flux[x][p[x]] -= flow;
    }
    return flow;
}

int edmondsKarp(int src, int dest) {
    int maxFlow = 0;
    while (int flow = bfs(src, dest)) {
        maxFlow += flow;
    }
    return maxFlow;
}

int main() {
    f >> n >> m;
    while(m--) {
        int x, y, c;
        f >> x >> y >> c;
        capacitate[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    g << edmondsKarp(1, n);
    return 0;
}