Cod sursa(job #3334240)

Utilizator tudorbarbuTudor Barbu tudorbarbu Data 17 ianuarie 2026 03:17:35
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include<fstream>
//#include <iostream>
#include<vector>
#include<queue>
#include<algorithm>
#define inf 1e9
using namespace std;

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

int n, m;

vector<vector<int>> graph;
vector<vector<int>> c;
vector <int> tata;
vector <bool> viz;


bool bfs() {
    tata.assign(n + 1, -1);
    viz.assign(n+1, 0);
    int source = 1;
    viz[source] = 1;
    queue<pair<int, int>> q;
    q.push({source, inf});
    while (!q.empty()) {
        int u = q.front().first;
        int flow = q.front().second;
        q.pop();
        for (auto v : graph[u]) {
            if (!viz[v] && c[u][v] > 0) {
                tata[v] = u;
                viz[v] = 1;
                int new_flow = min(flow, c[u][v]);
                if (v == n)
                    return true;
                q.push({v, new_flow});
            }
        }

    }
    return false;
}

int edmunds_karp() {
    int max_flow = 0;
    while (bfs()) {
        int flow_lant = inf;
        //bottleneck
        int curent = n;
        while (curent != 1) {
            int prev = tata[curent];
            flow_lant = min(flow_lant, c[prev][curent]);
            curent = prev;
        }
        curent = n;
        while (curent != 1) {
            int prev = tata[curent];

            c[prev][curent] -= flow_lant; // flux direct
            c[curent][prev] += flow_lant; // flux invers
            curent = prev;
        }
        max_flow += flow_lant;
    }
    return max_flow;
}

void citire() {
    fin >> n >> m;
    graph.resize(n+1);
    c.resize(n + 1, vector<int>(n + 1, 0));
    for (int i = 0 ; i < m; i++) {
        int u, v, w;
        fin >> u >> v >> w;
        graph[u].push_back(v);
        graph[v].push_back(u);
        c[u][v] = w;
    }
}


int main() {
    citire();
    fout << edmunds_karp() << endl;
}