Cod sursa(job #3334889)

Utilizator DalvDalvGhita Vladut DalvDalv Data 20 ianuarie 2026 15:09:37
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.66 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;


const int NMAX = 1000;
int n, m;
bool vis[NMAX + 1];
int p[NMAX + 1];
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
vector<vector<int>> graf(NMAX + 1);

int fluxMax_Bfs(int s, int d) {
    for (int i = 0; i <= n; i++) {
        vis[i] = false;
        p[i] = 0;
    }

    queue<int> q;
    q.push(s);
    vis[s] = true;
    while (!q.empty()) {
        int x = q.front();
        q.pop();

        for (auto y : graf[x]) {
            if (vis[y] || capacitate[x][y] - flux[x][y] <= 0) continue;

            vis[y] = true;
            p[y] = x;
            q.push(y);

            if (y == d) break;
        }
    }

    if (!vis[d]) return 0;

    vector<int> path;
    int x = d;
    while (x != 0) {
        path.push_back(x);
        x = p[x];
    }

    reverse(path.begin(), path.end());
    int bottleneck = 1e9;
    for (int i = 0; i < path.size() - 1; i++) {
        int x = path[i], y = path[i + 1];
        bottleneck = min(bottleneck, capacitate[x][y] - flux[x][y]);
    }
    for (int i = 0; i < path.size() - 1; i++) {
        int x = path[i], y = path[i + 1];
        flux[x][y] += bottleneck;
        flux[y][x] -= bottleneck;
    }

    return bottleneck;
}
void fluxMax() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    cin >> n >> m;

    for (int i = 0; i < m; i++) {
        int x, y, c;
        cin >> x >> y >> c;

        capacitate[x][y] = c;
        graf[x].push_back(y);
        graf[y].push_back(x);
    }

    int sum = 0;
    while (true) {
        int flux = fluxMax_Bfs(1, n);
        if (flux == 0) break;

        sum += flux;
    }
    cout << sum;
}

// void topoSort() {
//     ifstream cin("sortaret.in");
//     ofstream cout("sortaret.out");
//
//     int n, m;
//     cin >> n >> m;
//
//     vector<vector<int>> graf(n + 1);
//     vector<int> grad(n + 1, 0);
//     for (int i = 0; i < m; i++) {
//         int x, y;
//         cin >> x >> y;
//
//         grad[y]++;
//         graf[x].push_back(y);
//     }
//
//     queue<int> q; // Pentru minim lexicografic trebuie priority_queue
//     for (int i = 1; i <= n; i++) {
//         if (grad[i] != 0) continue;
//         q.push(i);
//     }
//
//     vector<int> result;
//     while (!q.empty()) {
//         int x = q.front();
//         q.pop();
//
//         result.push_back(x);
//
//         for (auto y : graf[x]) {
//             grad[y]--;
//             if (grad[y] != 0) continue;
//
//             q.push(y);
//         }
//     }
//
//     for (auto x : result) {
//         cout << x << " ";
//     }
//     cout << endl;
// }

int main() {
    fluxMax();
    return 0;
}