Cod sursa(job #3336821)

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

using namespace std;

const int N = 1001;
int n, m;
int c[N][N], f[N][N], p[N];
vector<int> adj[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, fluxcrt] = q.front();
		q.pop();
		for (auto v: adj[u])
		{
			if (!viz[v] && c[u][v] - f[u][v] > 0)
			{
				viz[v] = true;
				p[v] = u;
				int fluxtmp = min(fluxcrt, c[u][v] - f[u][v]);
				if (v == t)
				{
					int crt = v;
					while (crt != s)
					{
						int prec = p[crt];
						f[prec][crt] += fluxtmp;
						f[crt][prec] -= fluxtmp;
						crt = prec;
					}
					return fluxtmp;
				}
				q.push({v, fluxtmp});
			}
		}
	}
	return 0;
}


int main()
{
	fin >> n >> m;
	for (int i = 1; i <= m; ++i)
	{
		int u, v, cost;
		fin >> u >> v >> cost;
		adj[u].push_back(v);
		adj[v].push_back(u);
		c[u][v] += cost;
	}
	int s = 1;
	int t = n;
	int fluxmax = 0;
	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;
}