Cod sursa(job #3262918)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 12 decembrie 2024 10:42:07
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;

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

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

int bfs(int s, int d) {
    for(int i = 1; i <= n; i++) {
        p[i] = 0;
        vis[i] = 0;
    }
    queue<int> q;
    q.push(s);
    vis[s] = 1;
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        for(auto vecin : G[node]) {
            if(!vis[vecin]) {
                if(capacitate[node][vecin] - flux[node][vecin] > 0) {
                    q.push(vecin);
                    vis[vecin] = 1;
                    p[vecin] = node;
                }
            }
        }
    }
    if(!vis[d]) {
        return 0;
    }
    vector<int> path;
    int x = d;
    while(x != 0) {
        path.push_back(x);
        x = p[x];
    }
    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, 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] += flow;
        flux[y][x] -= flow;
    }
    return flow;

}


int main() {

    f >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        capacitate[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    int maxFlow = 0;
    while(1) {
        int flow = bfs(1, n);
        if(flow == 0) {
            break;
        }
        maxFlow += flow;
    }
    g << maxFlow;
    return 0;
}