Cod sursa(job #3264238)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 19 decembrie 2024 16:55:56
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
//Edmonds-Karp - O(min(V*E^2, E*Fmax))

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]) {
                if(capacitate[node][vecin] - flux[node][vecin] > 0) {
                    q.push(vecin);
                    vis[vecin] = 1;
                    p[vecin] = node;

                }
            }
        }
    }
    if(vis[dest] == 0) {
        return 0;
    }
    vector<int> path;
    int x = dest;
    while(x != 0) {
        path.push_back(x);
        x = p[x];
    }
    reverse(path.begin(), path.end());
    int flow = 1e9;
    for(int i = 0; i < (int)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 < (int)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;
    while(m--) {
        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;
}