Cod sursa(job #3377480)

Utilizator calin06calin mihaescu calin06 Data 23 noiembrie 2026 14:41:49
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <fstream>

using namespace std;

const int nmax = 2005;
vector<int> g[nmax + 1];
long long capacitate[nmax + 1][nmax + 1];
long long flux[nmax + 1][nmax + 1];
int n, m;

long long ek(int sursa, int destinatie) {
    vector<int> p(nmax + 1, 0), viz(nmax + 1, 0);
    queue<int> q;
    q.push(sursa);
    viz[sursa] = 1;

    while (q.empty() == false) {
        int nod = q.front();
        q.pop();

        for (int vecin : g[nod]) {
            if (viz[vecin] == false && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
                q.push(vecin);
                viz[vecin] = 1;
                p[vecin] = nod;
            }
        }
    }

    if (viz[destinatie] == 0)
        return 0;

    vector<int> drum;
    int x = destinatie;

    while (x != sursa) {
        drum.push_back(x);
        x = p[x];
    }

    drum.push_back(sursa);
    reverse(drum.begin(), drum.end());

    long long flow_nou = (1LL << 60);
    for (int i = 0; i + 1 < drum.size(); i++) {
        int u = drum[i];
        int v = drum[i + 1];
        flow_nou = min(flow_nou, capacitate[u][v] - flux[u][v]);
    }

    for (int i = 0; i + 1 < drum.size(); i++) {
        int u = drum[i];
        int v = drum[i + 1];
        flux[u][v] += flow_nou;
        flux[v][u] -= flow_nou;
    }

    return flow_nou;
}

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

    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int a, b;
        long long c;
        fin >> a >> b >> c;
        g[a].push_back(b);
        g[b].push_back(a);
        capacitate[a][b] += c;
    }

    long long sum = 0;
    while (true) {
        long long f = ek(1, n);
        if (f == 0)
            break;
        else
            sum += f;
    }

    fout << sum << "\n";
    return 0;
}