Cod sursa(job #3291054)

Utilizator adelinapetreAdelina Petre adelinapetre Data 3 aprilie 2025 10:43:28
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

ifstream cin("maxflow.in");
ofstream cout("maxflow.out");

const int Nmax = 1005;

int adj[Nmax][Nmax], cap[Nmax][Nmax], flow[Nmax][Nmax];
int pre[Nmax];
vector<int> drum;
bool vis[Nmax];

int n;
void bfs(int nod)
{
	queue<int> q;
	for (int i = 1; i <= n; i++)
		vis[i] = 0;
	q.push(nod);
	vis[nod] = 1;
	while (!q.empty())
	{
		nod = q.front();
		q.pop();
		for(int i = 1; i <= n; i ++)
			if (adj[nod][i] && vis[i] == 0 && cap[nod][i] - flow[nod][i] > 0)
			{
				q.push(i);
				pre[i] = nod;
				vis[i] = 1;
			}
	}
}

int ans = 0;
void builddrum(int nod)
{
	drum.clear();
	drum.push_back(n);
	while (nod != 0)
	{
		drum.push_back(nod);
		nod = pre[nod];
	}
	reverse(drum.begin(), drum.end());
	if (drum[0] != 1)
		return;
	int minn = 1e9;
	for (int i = 0; i + 1 < drum.size(); i++)
	{
		int a = drum[i], b = drum[i + 1];
		if (cap[a][b] - flow[a][b] == 0)
		{
			minn = 0;
			break;
		}
		minn = min(minn, cap[a][b] - flow[a][b]);
	}
	if (minn == 0)
		return;
	ans += minn;
	for (int i = 0; i + 1 < drum.size(); i++)
	{
		int a = drum[i], b = drum[i + 1];
		flow[a][b] += minn;
		flow[b][a] -= minn;
	}
}

int main()
{
	int m, a, b, c;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		cin >> a >> b >> c;
		cap[a][b] += c;
		adj[a][b] = 1;
		adj[b][a] = 1;
	}
	bool ok = 1;
	while (ok == 1)
	{
		ok = 0;
		bfs(1);
		if (vis[n] == 1)
		{
			ok = 1;
			for(int i = 1; i < n; i ++)
				if (vis[i] == 1 && adj[i][n] == 1 && cap[i][n] - flow[i][n] > 0)
					builddrum(i);
		}
	}
	cout << ans;
}