Cod sursa(job #2962079)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 7 ianuarie 2023 18:44:04
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define cin f
#define cout g

//	am rezolvat initial cu algoritmul Edmonds-Karp, dar fara optimizare
//	pentru optimizare m am inspirat de aici:
//	https://www.infoarena.ro/job_detail/2961888?action=view-source

//	the matrix capacity stores the residual network capacity
int n, m;
vector<int> parent;
vector<unordered_map<int, int>> capacity;
vector<unordered_map<int, int>> adj;

bool bfs(int s, int t)
{
	fill(parent.begin(), parent.end(), -1);
	parent[s] = -2;

	queue<int> Q;
	Q.push(s);

	while(! Q.empty())
	{
		int cur = Q.front();
		Q.pop();

		for(auto &edge : capacity[cur])
		{
			if(parent[edge.first] == -1 and edge.second != 0)
			{
				parent[edge.first] = cur;

				if(edge.first == t)
					return true;

				Q.push(edge.first);
			}
		}
	}

	return false;
}

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

	while(bfs(s, t))
	{
		for(auto &edge : capacity[t])
		{
			int cur = edge.first;
			if(capacity[cur][t] == 0 || parent[cur] == -1)
				continue;

			int new_flow = INT_MAX;
			new_flow = min(new_flow, capacity[cur][t]);

			while(cur != s)
			{
				int prev = parent[cur];
				new_flow = min(new_flow, capacity[prev][cur]);
				if(new_flow == 0)
					break;
				cur = prev;
			}

			if(new_flow == 0)
				continue;
			flow += new_flow;

			cur = edge.first;
			capacity[cur][t] -= new_flow;
			capacity[t][cur] += new_flow;

			while(cur != s)
			{
				int prev = parent[cur];
				capacity[prev][cur] -= new_flow;
				capacity[cur][prev] += new_flow;
				cur = prev;
			}
		}
	}

	return flow;
}

int main()
{
	cin >> n >> m;
	parent.resize(n + 1);
	capacity.resize(n + 1);
	adj.resize(n + 1);

	for(int i = 1; i <= m; i ++)
	{
		int x, y, c;
		cin >> x >> y >> c;

		adj[x][y] = c;
		capacity[x][y] = c;
		if(capacity[y].find(x) == capacity[y].end())
			capacity[y][x] = 0;
	}

	cout<<maxflow(1, n)<<'\n';

	return 0;
}