Cod sursa(job #3272260)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 29 ianuarie 2025 00:14:26
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;


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

int n, m, g[1005][1005], viz[1005], parent[1005];

int Bfs() {
    queue<int>q;
    for (int i = 1; i <= n; i++)
        viz[i] = parent[i] = 0;
    q.push(1);
    viz[1] = 1;

    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        if (nod == n)
            return true;
        for (int i = 1; i <= n; i++)
            if (g[nod][i] > 0 && !viz[i]) {
                viz[i] = 1;
                parent[i] = nod;
                q.push(i);
            }
    }
    return false;
}

int Flow() {
    int maxFlow = 0;
    while (Bfs()) {
        for (int i = 1; i < n; i++) {
            if (g[i][n] > 0 && viz[i]) {
                vector<int>path;
                int leaf = i;
                int nod = parent[leaf];
                path.push_back(n);
                path.push_back(i);
                while (nod != 1) {
                    path.push_back(nod);
                    nod = parent[nod];
                }
                path.push_back(1);
                int flowMin = INT_MAX;
                //                cout << "!";
                for (int j = 0; j < path.size() - 1; j++)
                    flowMin = min(flowMin, g[path[j + 1]][path[j]]);
                //                cout << flowMin << " ";
                maxFlow += flowMin;

                for (int j = 0; j < path.size() - 1; j++) {
                    g[path[j + 1]][path[j]] -= flowMin;
                    g[path[j]][path[j + 1]] += flowMin;
                }
            }
        }
    }
    return maxFlow;
}

int main()
{
    int x, y, flow;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> flow;
        g[x][y] += flow;
    }
    fout << Flow() << "\n";
    return 0;
}