Cod sursa(job #3336822)

Utilizator emilianvatavucristianEmilian Vatavu Cristian emilianvatavucristian Data 26 ianuarie 2026 05:57:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 1001;
int n, m;
vector<int> adj[N];
int capacitate[N][N], flux[N][N], tata[N];
bool viz[N];

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int bfs(int s, int t)
{
	queue<pair<int, int>> q;
	q.push({s, INT_MAX});
	viz[s] = true;
	while (!q.empty())
	{
		auto [u, f] = q.front();
		q.pop();
		for (auto v : adj[u])
		{
			if (!viz[v] && flux[u][v] < capacitate[u][v])
			{
				viz[v] = true;
				tata[v] = u;
				int fluxnou = min(f, capacitate[u][v] - flux[u][v]);
				if (v == t)
				{
					int crt = v;
					while (crt != s)
					{
						int t = tata[crt];
						flux[t][crt] += fluxnou;
						flux[crt][t] -= fluxnou;
						crt = t;
					}
					return fluxnou;
				}
				q.push({v, fluxnou});
			}
		}
	}
	return 0;
}

int main()
{
	fin >> n >> m;
	for (int i = 1; i <= m; ++i)
	{
		int u, v, c;
		fin >> u >> v >> c;
		adj[u].push_back(v);
		adj[v].push_back(u);
		capacitate[u][v] = c;
	}
	int fluxmax = 0;
	int s = 1, t = n;
	while (true)
	{
		int flux = bfs(s, t);
		if (flux == 0)
		{
			break;
		}
		fluxmax += flux;
		for (int i = 1; i <= n; ++i)
		{
			viz[i] = false;
		}
	}
	fout << fluxmax << '\n';
	fin.close();
	fout.close();
	return 0;
}