Cod sursa(job #3328599)

Utilizator denis_cristeaCristea Denis-Adrian denis_cristea Data 9 decembrie 2025 13:14:44
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <queue>
#include <fstream>
#include <vector>

const int N_MAX = 1e3;
int capacitate[N_MAX + 1][N_MAX + 1];
int flux[N_MAX + 1][N_MAX + 1];
int vis[N_MAX + 1], p[N_MAX + 1];

std::vector<int> G[N_MAX + 1];

int n, m;

int bfs(int s, int d) {
    for(int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[i] = 0;
    }
    
    std::queue<int> q;
    q.push(s);
    vis[s] = 1;

    while(!q.empty()) {
        int nod = q.front();
        q.pop();
        for (auto vecin : G[nod]) {
            if(!vis[vecin] && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
                vis[vecin] = 1;
                p[vecin] = nod;
                q.push(vecin);
            }
        }
    }

    if(!vis[d]) {
        return 0;
    }

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

    std::reverse(path.begin(), path.end());
    int flow = 1e9;

    for (int i = 0; i < path.size() - 1; i++) {
        int a = path[i];
        int b = path[i + 1];
        flow = std::min(flow, capacitate[a][b] - flux[a][b]);
    }

    for (int i = 0; i < path.size() - 1; i++) {
        int a = path[i];
        int b = path[i + 1];
        flux[a][b] += flow;
        flux[b][a] -= flow;
    }

    return flow;

}

int main() {
	std::ifstream fin("maxflow.in");
    std::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;
        G[x].push_back(y);
        G[y].push_back(x);
    }

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

    fout << maxflow;
}