Cod sursa(job #2962301)

Utilizator NefelibataAnton Marius Alexandru Nefelibata Data 8 ianuarie 2023 10:23:48
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<climits>

using namespace std;
ifstream f("maxflow.in");
ofstream o("maxflow.out");
int n, m, x, y, z, s, d;
int c[5000][5000];
vector<vector<int>> g;
int tata[5000];

bool bfs() {
    queue<int> q;
    int vizitat[n+1];
    for(int i=1 ; i<=n; ++i) vizitat[i] = 0;
    q.push(s);
    tata[s] = -1;
    vizitat[s] = 1;
    while(!q.empty()){
        int u = q.front();
        q.pop();
        for(auto v : g[u]) {
            if(!vizitat[v] && c[u][v]) {
                tata[v] = u;
                if (v == d) return 1;
                vizitat[v] = 1;
                q.push(v);
            }
        }
    }
    return 0;
}

int flux_maxim() {
    int fluxmax = 0;
    while (bfs()) {
        int u, v = d, flux = INT_MAX;
        while(v!=s) {
            u = tata[v];
            if(c[u][v] < flux) flux = c[u][v];
            v = tata[v];
        }
        v = d;

        while(v != s) {
            u = tata[v];
            c[v][u] += flux;
            c[u][v] -= flux;
            v = tata[v];
        }
        fluxmax += flux;
    }
    return fluxmax;
}

int main() {
    f>>n>>m;
    s = 1;
    d = n;
    g.resize(n+1);

    for(int i = 0; i<m; ++i){
        f>>x>>y>>z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }

    o<<flux_maxim();
    f.close();
    o.close();
    return 0;
}