Cod sursa(job #2988970)

Utilizator Radu_TudorRadu Tudor Radu_Tudor Data 5 martie 2023 17:21:53
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#include <limits.h>

#define ll long long

using namespace std;

const string FILE_NAME = "maxflow";
const int N_MAX = 1e3 + 1;

ifstream fin(FILE_NAME + ".in");
ofstream fout(FILE_NAME + ".out");

ll N, M;
ll flows[N_MAX][N_MAX];

ll source = 1;
ll sink;

ll sink_flow;

vector<pair<ll, ll>> edges[N_MAX];

void read() {

	fin >> N >> M;

	int from, to, capacity;
	for (int i = 1; i <= M; i++) {

		fin >> from >> to >> capacity;

		edges[from].push_back(make_pair(to, capacity));
		edges[to].push_back(make_pair(from, capacity));

		flows[from][to] = capacity;
	}

	sink = N;
}

ll bfs(vector<int>& parent) {

	fill(parent.begin(), parent.end(), -1);
	parent[source] = -2;

	queue<pair<ll, ll>> Q;
	Q.push({ source, INT_MAX });

	while (Q.empty() == false) {

		ll current_node = Q.front().first;
		ll flow = Q.front().second;

		Q.pop();

		for (size_t i = 0; i < edges[current_node].size(); i++) {

			ll neighbour = edges[current_node][i].first;

			if (parent[neighbour] == -1 && flows[current_node][neighbour]) {

				parent[neighbour] = current_node;

				ll new_flow = min(flow, flows[current_node][neighbour]);

				if (neighbour == sink)
					return new_flow;

				Q.push({ neighbour, new_flow });
			}
		}
	}

	return 0;
}

void solve() {

	vector<int> parent(N + 1);

	while (1) {

		ll new_flow = bfs(parent);

		if (new_flow == 0)
			break;

		sink_flow += new_flow;

		ll current_node = sink,
			prev;
		while (current_node != source) {

			prev = parent[current_node];

			flows[prev][current_node] -= new_flow;

			current_node = prev;
		}
	}
}

void display() {

	fout << sink_flow;
}

int main() {

	read();
	solve();
	display();

	fin.close();
	fout.close();

	return 0;
}