Cod sursa(job #3259933)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 28 noiembrie 2024 15:29:27
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

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

int bfs(int s, int d) {
    queue<int> q;
    q.push(s);
    for(int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[i] = 0;
    }
    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 -1;
    }
    int mn = 1e9;
    vector<int> path;
    while(d != 0) {
        path.push_back(d);
        if(p[d] != 0) {
            mn = min(mn, capacitate[p[d]][d] - flux[p[d]][d]);
        }
        d = p[d];
    }
    reverse(path.begin(), path.end());
    for(int i = 0; i < path.size() - 1; i++) {
        flux[path[i]][path[i + 1]] += mn;
        flux[path[i + 1]][path[i]] -= mn;
    }
    return mn;

}

int main() {
    ifstream f("maxflow.in");
    ofstream g("maxflow.out");
    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);
    }
    //cout << bfs(1, n);
    int maxFlow = 0;
    int cnt = 3;
    while(cnt--) {
        int flow = bfs(1, n);
        //cout << flow << ' ';
        if(flow == -1) {
            break;
        }
        maxFlow += flow;
    }
    g << maxFlow;
    return 0;
}