Cod sursa(job #2604514)

Utilizator MarcGrecMarc Grec MarcGrec Data 22 aprilie 2020 20:00:40
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#define MAX_N 1000

#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;

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

struct edge
{
	edge(int _u, int _v, int _flow, int _capacity) :
		u(_u),
		v(_v),
		flow(_flow),
		capacity(_capacity)
	{
	}
	
	int u, v, flow, capacity;
	edge* reverse;
};

int n, m, maxFlow;
vector<edge> G[MAX_N + 1];

bool FindPath();

int main()
{
	fin >> n >> m;
	for (int i = 0, x, y, c; i < m; ++i)
	{
		fin >> x >> y >> c;
		
		G[x].emplace_back(x, y, 0, c);
		G[y].emplace_back(y, x, 0, 0);
		
		G[x].back().reverse = &G[y].back();
		G[y].back().reverse = &G[x].back();
	}
	
	while (FindPath());
	
	fout << maxFlow;
	
	fin.close();
	fout.close();
	return 0;
}

bool FindPath()
{
	edge* F[MAX_N + 1] = {  };
	
	queue<int> Q;
	Q.push(1);
	
	while (!Q.empty())
	{
		int curr = Q.front();
		Q.pop();
		
		for (edge& e : G[curr])
		{
			if ((F[e.v] == nullptr) && (e.capacity > e.flow) && (e.v != 1))
			{
				F[e.v] = &e;
				Q.push(e.v);
			}
		}
	}
	
	if (F[n] == nullptr)
	{
		return false;
	}
	
	int pushFlow = INT_MAX;
	for (edge* e = F[n]; e != nullptr; e = F[e->u])
	{
		pushFlow = min(pushFlow, e->capacity - e->flow);
	}
	
	for (edge* e = F[n]; e != nullptr; e = F[e->u])
	{
		e->flow += pushFlow;
		e->reverse->flow -= pushFlow;
	}
	
	maxFlow += pushFlow;
	return true;
}