Cod sursa(job #3327834)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 5 decembrie 2025 14:25:35
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;

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

}

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;
        capacitate[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
        //capacitate[y][x] = 0;
    }
    int sum = 0;
    while(1) {
        int flux = bfs(1, n);
        sum += flux;
        if(flux == 0) {
            break;
        }
    }
    cout << sum;
}