Cod sursa(job #2962655)

Utilizator RaduAntoneoAntonio Alexandru Radu RaduAntoneo Data 8 ianuarie 2023 22:25:56
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define cin f
#define cout g

int n, m;
vector<int> prevs;
vector<vector<int>> capacity;
vector<vector<int>> adj;

int bfs(int s, int t, vector<int>& prevs) {
    fill(prevs.begin(), prevs.end(), -1);
    prevs[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INT_MAX});

    while (!q.empty()) {
        int curr = q.front().first;
        int flow = q.front().second;
        q.pop();

        for (int next : adj[curr]) {
            if (prevs[next] == -1 && capacity[curr][next]) {
                prevs[next] = curr;
                int new_flow = min(flow, capacity[curr][next]);
                if (next == t)
                    return new_flow;
                q.push({next, new_flow});
            }
        }
    }
    return 0;
}

int maxflow(int s, int t) {
    int flow = 0;
    int new_flow;

    while (new_flow = bfs(s, t, prevs)) {
        flow += new_flow;
        int curr = t;
        while (curr != s) {
            int prev = prevs[curr];
            capacity[prev][curr] -= new_flow;
            capacity[curr][prev] += new_flow;
            curr = prev;
        }
    }

    return flow;
}

int main() {
	cin >> n >> m;
	prevs.resize(n+1);
	capacity.resize(n+1, vector<int>(n+1));
	adj.resize(n+1);

	for(int i = 1; i <= m; i ++) {
		int a, b, c;
		cin >> a >> b >> c;
		adj[a].push_back(b);
		adj[b].push_back(a);
		capacity[a][b] = c;
	}

	cout << maxflow(1, n) << '\n';
	return 0;
}