Cod sursa(job #2967043)

Utilizator agabi21Totolici Alexandru agabi21 Data 18 ianuarie 2023 22:26:27
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define INF 0x3f3f3f3f

int n, m, s, t;
int flow[1001][1001], capacitate[1001][1001], parinte[1001];
vector<int> graf[1001];

bool bfs() {
    memset(parinte, -1, sizeof(parinte));
    queue<int> q;
    q.push(s);
    parinte[s] = -2;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : graf[u]) {
            if (parinte[v] == -1 && capacitate[u][v] - flow[u][v] > 0) {
                parinte[v] = u;
                q.push(v);
                if (v == t) {
                    return true;
                }
            }
        }
    }
    return false;
}

int max_flow() {
    int max_flow = 0;
    while (bfs()) {
        int min_flow = INF;
        for (int v = t; v != s; v = parinte[v]) {
            int u = parinte[v];
            min_flow = min(min_flow, capacitate[u][v] - flow[u][v]);
        }
        for (int v = t; v != s; v = parinte[v]) {
            int u = parinte[v];
            flow[u][v] += min_flow;
            flow[v][u] -= min_flow;
        }
        max_flow += min_flow;
    }
    return max_flow;
}

int main() {
    f >> n >> m;
    s = 1;
    t = n;
    for (int i = 0; i < m; i++) {
        int u, v, c;
        f >> u >> v >> c;
        graf[u].push_back(v);
        graf[v].push_back(u);
        capacitate[u][v] = c;
    }
    g << max_flow() << endl;
    return 0;
}