Cod sursa(job #2958763)

Utilizator mihneagherghelMihnea Gherghel-Butan mihneagherghel Data 28 decembrie 2022 09:35:26
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;

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

// variabile
int n, m;
vector<vector<int>> lista_adiacenta;
int costuri[1001][1001];
int tata[1001];
int flux[1001][1001];
vector<int> viz;

void citire()
{
	fin >> n >> m;
	int a, b, c;
	lista_adiacenta = vector<vector<int>>(n+1, vector<int>());
	for (int i = 0; i < m; i++)
	{
		fin >> a >> b >> c;
		lista_adiacenta[a].push_back(b);
		lista_adiacenta[b].push_back(a);
		costuri[a][b] = c;
	}
}
bool construieste_lant()
{
	viz = vector<int>(n + 1, 0);
	queue<int> coada;
	coada.push(1);
	viz[1] = 1;
	tata[1] = 0;
	while (!coada.empty() )
	{
		int nod = coada.front();
		coada.pop();
		if (nod == n)
			continue;
		for (auto j : lista_adiacenta[nod])
		{
			if (viz[j] == 0 && costuri[nod][j]-flux[nod][j] > 0)
			{
				coada.push(j);
				viz[j] = 1; tata[j] = nod;
			}
		}
		if (viz[n] == 1)
		{
			return true;
		}
	}
	return false;
}
int main()
{
	citire();
	int fluxmaxim = 0;
	while (construieste_lant()) 
	{
		int iP = 110001; //i(P)
		int t = n;
		while (t != 1) {
			if (costuri[tata[t]][t]-flux[tata[t]][t]< iP)
				iP = costuri[tata[t]][t]-flux[tata[t]][t];
			t = tata[t];
		}
		t = n;
		while (t != 1)
		{
			flux[tata[t]][t] += iP;
			flux[t][tata[t]] -= iP;
			t = tata[t];
		}
		fluxmaxim += iP;
	}
	fout << fluxmaxim;
}