Cod sursa(job #3187299)

Utilizator TheGodFather2131Alexandru Miclea TheGodFather2131 Data 28 decembrie 2023 13:21:24
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
//ALEXANDRU MICLEA
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

//VARIABLES

int inf = 1e9 + 7;
int n, m;

int capacitate[1005][1005];
int flux[1005][1005];
int tata[1005];

vector<int> gr[1005];
queue<int> q;

//FUNCTIONS

int drum_ameliorare() {
    for (auto& x : tata) x = 0;

    tata[1] = 1;
    q.push(1);
    int ok = 0;

    while (!q.empty()){
        int nod = q.front();
        q.pop();
        if (nod == n) {
            tata[n] = nod;
            ok = 1;
            continue;
        }

        for (auto& x : gr[nod]) {
            if (!tata[x] && capacitate[nod][x] - flux[nod][x] > 0){
                tata[x] = nod;
                q.push(x);
            }
        }
    }

    return ok;
}

//MAIN
int main() {

#ifdef INFOARENA
    ifstream fin("maxflow.in"); ofstream fout("maxflow.out");
    cin.rdbuf(fin.rdbuf()); cout.rdbuf(fout.rdbuf());
#endif

    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, val;
        cin >> x >> y >> val;

        capacitate[x][y] += val;
        gr[x].push_back(y);
        gr[y].push_back(x);
    }

    int ans = 0;

    while (drum_ameliorare()) {
        for (auto& x : gr[n]) {
            if (!tata[x]) continue;
            //tata[n] = x;
            int nod_curent = n;
            int flux_minim = inf;

            while (nod_curent != 1) {
                flux_minim = min(flux_minim, capacitate[tata[nod_curent]][nod_curent] - flux[tata[nod_curent]][nod_curent]);
                nod_curent = tata[nod_curent];
            }

            nod_curent = n;

            while (nod_curent != 1) {
                flux[tata[nod_curent]][nod_curent] += flux_minim;
                flux[nod_curent][tata[nod_curent]] -= flux_minim;
                nod_curent = tata[nod_curent];
            }
            ans += flux_minim;
        }
    }

    cout << ans;

    return 0;
}