Cod sursa(job #2724960)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 18 martie 2021 10:18:37
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, f[1024][1024], c[1024][1024], t[1024];
vector<int> g[1024];
bool v[1024];

bool bfs() {
    queue<int> q;
    q.push(1);
    v[1] = true;
    for(int i = 1; i <= n; i++) v[i] = false;

    while(!q.empty()) {
        int x = q.front();
        q.pop();

        for(auto next: g[x])
            if(!v[next] && f[x][next] < c[x][next]) {
                v[next] = true;
                t[next] = x;
                q.push(next);
            }
    }
    return v[n];
}

int main() {
    fin >> n >> m;
    while(m--) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }

    int flow;
    for(flow = 0; bfs(); ) {
        for(auto tt: g[n]) {
            if(!v[tt] || f[tt][n] >= c[tt][n]) continue;
            t[n] = tt;

            int fmin = 2e9;
            for(int i = n; i != 1 ; i = t[i])
                fmin = min(fmin, c[t[i]][i]-f[t[i]][i]);
            for(int i = n; i != 1 ; i = t[i]) {
                f[t[i]][i] += fmin;
                f[i][t[i]] -= fmin;
            }
            flow += fmin;
        }
    }

    fout << flow;
}