Cod sursa(job #3336364)

Utilizator RaluccccaNegru Raluca Ralucccca Data 24 ianuarie 2026 17:08:07
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <fstream>
using namespace std;

const int MAX = 1000;
const int INF = 1e9;
int capacitate[MAX + 1][MAX + 1], flux[MAX + 1][MAX + 1];
vector<int> G[MAX + 1];
int viz[MAX + 1], tata[MAX + 1];
int n, m, maxflow;

int bfs() {
    for (int i = 1; i <= n; i++) {
        viz[i] = tata[i] = 0;
    }
    queue<int> q;
    q.push(1);
    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        if (viz[nod] == 0) {
            viz[nod] = 1;
            for (const auto &vecin: G[nod]) {
                if (viz[vecin] == 0 && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
                    q.push(vecin);
                    tata[vecin] = nod;
                }
            }
        }
    }
    if (viz[n] == 0) {
        return 0;
    }
    stack<int> st;
    int nod = n;
    while (nod != 0) {
        st.push(nod);
        nod = tata[nod];
    }
    vector<int> drum;
    int flow = INF;
    while (!st.empty()) {
        drum.push_back(st.top());
        st.pop();
    }
    for (int i = 0; i < drum.size() - 1; i++) {
        int x = drum[i];
        int y = drum[i + 1];
        if (flow > capacitate[x][y] - flux[x][y]) {
            flow = capacitate[x][y] - flux[x][y];
        }
    }
    for (int i = 0; i < drum.size() - 1; i++) {
        int x = drum[i];
        int y = drum[i + 1];
        flux[x][y] += flow;
        flux[y][x] -= flow;
    }
    return flow;
}

int main() {
    ifstream fin("maxflow.in");
    ofstream fout("maxflow.out");
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        capacitate[x][y] = c;
        //mergem pe graful rezidual
        G[x].push_back(y);
        G[y].push_back(x);
    }

    while (true) {
        int flow = bfs();
        if (flow == 0) {
            break;
        }
        maxflow += flow;
    }

    fout << maxflow;
    return 0;
}