Cod sursa(job #3329246)

Utilizator cosminqfDanciu Cosmin Alexandru cosminqf Data 12 decembrie 2025 14:34:06
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e3;
int cap[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 s, int d) {
    for(int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[i] = 0;
    }
    queue<int> q;
    q.push(s);
    vis[s] = 1;
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(auto vecin : G[x]) {
            if(!vis[vecin] && cap[x][vecin] - flux[x][vecin] > 0) {
                vis[vecin] = 1;
                p[vecin] = x;
                q.push(vecin);
            }
        }
    }
    if(!vis[d]) {
        return 0;
    }
    vector<int> path;
    while(d != 0) {
        path.push_back(d);
        d = p[d];
    }
    reverse(path.begin(), path.end());
    int flow = 1e9;
    for(int i = 0; i < path.size() - 1; i++) {
        int x = path[i];
        int y = path[i + 1];
        flow = min(flow, cap[x][y] - flux[x][y]);
    }
    for(int i = 0; i < path.size() - 1; i++) {
        int x = path[i];
        int y = path[i + 1];
        flux[x][y] += flow;
        flux[y][x] -= flow;
    }
    return flow;

}

int main() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        cap[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    int maxflow = 0;
    //cout << bfs(1, n);
    while(true) {
        int flow = bfs(1, n);
        if(flow == 0) {
            break;
        }
        maxflow += flow;
    }
    cout << maxflow;
	return 0;
}