Cod sursa(job #3228867)

Utilizator David8406Marian David David8406 Data 11 mai 2024 17:35:20
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

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

int n, m, flux;
vector<int> v[1005];
int capacitate[1005][1005], flow[1005][1005], parent[1005];
queue<int> q;
bool viz[1005];

void bfs(int nod) {
    for (int i = 1; i <= n; i++) {
        viz[i] = 0;
        parent[i] = 0;
    }
    viz[nod] = 1;
    q.push(nod);
    while (!q.empty()) {
        int cr = q.front();
        q.pop();
        if (cr == n) continue;
        for (auto el : v[cr])
            if (!viz[el] && capacitate[cr][el] != flow[cr][el]) {
                viz[el] = 1;
                parent[el] = cr;
                q.push(el);
            }
    }
}

int main(){
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back(y);
        v[y].push_back(x);
        capacitate[x][y] = c;
    }
    while (1) {
        bfs(1);
        if (!viz[n]) break;
        for (auto el : v[n]) {
            if (!viz[el]) continue;
            parent[n] = el;
            int cr = n, mn = 1e9;
            while (cr != 1) {
                if (mn == 0) break;
                mn = min(mn, capacitate[parent[cr]][cr] - flow[parent[cr]][cr]);
                cr = parent[cr];
            }
            if (mn == 0) continue;
            flux += mn;
            cr = n;
            while (cr != 1) {
                flow[parent[cr]][cr] += mn;
                flow[cr][parent[cr]] -= mn;
                cr = parent[cr];
            }
        }
    }
    fout << flux;
}