Cod sursa(job #3220719)

Utilizator diana_dd03Dorneanu Diana diana_dd03 Data 4 aprilie 2024 18:09:30
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int c[1002][1002], f[1002][1002], n, m;
vector<int> L[1002];
int S, D, t[1002], fluxMax;
/// t[i] = predecesorul nodului i din drumul
///      de la S la i

/// ret. daca ajungem in D
int BFS(){
    int k, i;
    queue<int> q;
    for (i = 1; i <= n; i++)
        t[i] = 0;
    q.push(S);
    t[S] = -1;
    while (!q.empty()){
        k = q.front();
        q.pop();
        for (int i : L[k])
            if (t[i] == 0 && c[k][i] > f[k][i]){
                t[i] = k;
                q.push(i);
            }
    }
    return (t[D] != 0);
}

void Dinic(){
    int i, j, r;
    fluxMax = 0;
    while (BFS() != 0){
        for (i = 1; i <= n; i++)
            if (i != S && i != D && c[i][D]>f[i][D]){
                r = c[i][D] - f[i][D];
                j = i;
                while (j != S){
                    r = min(r, c[t[j]][j]-f[t[j]][j]);
                    j = t[j];
                }
                if (r == 0) continue;
                fluxMax += r;
                f[i][D] += r;
                f[D][i] -= r;
                j = i;
                while (j != S){
                    f[t[j]][j] += r;
                    f[j][t[j]] -= r;
                    j = t[j];
                }
            }
    }
    fout << fluxMax << "\n";
}

int main(){
    int i, x, y, cost;
    fin >> n >> m;
    for (i = 1; i <= m; i++){
        fin >> x >> y >> cost;
        c[x][y] = cost;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    S = 1; D = n;
    Dinic();
    fout.close();
    return 0;
}