Cod sursa(job #3228856)

Utilizator David8406Marian David David8406 Data 11 mai 2024 17:16:36
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 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();
        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;
        int cr = n, mn = 1e9;
        while (cr != 1) {
            mn = min(mn, capacitate[parent[cr]][cr] - flow[parent[cr]][cr]);
            cr = parent[cr];
        }
        flux += mn;
        cr = n;
        while (cr != 1) {
            flow[parent[cr]][cr] += mn;
            flow[cr][parent[cr]] -= mn;
            cr = parent[cr];
        }
    }
    fout << flux;
}