Cod sursa(job #1076639)

Utilizator fhandreiAndrei Hareza fhandrei Data 10 ianuarie 2014 14:22:31
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
// Include
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

// Definitii
#define pb push_back

// Constante
const int sz = 1001;
const int source = 1;
const int oo = (1<<30)-1;

// Functii
bool bfs();

// Variabile
ifstream in("flow.in");
ofstream out("flow.out");

int destination, edges;
int maxFlow;

int father[sz];

int emptySpace[sz][sz];
vector<int> graph[sz];

// Main
int main()
{
	in >> destination >> edges;
	
	int rFrom, rTo, rCapacity;
	while(edges--)
	{
		in >> rFrom >> rTo >> rCapacity;
		graph[rFrom].pb(rTo);
		graph[rTo].pb(rFrom);
		
		emptySpace[rFrom][rTo] = rCapacity;
	}
	
	while(bfs())
	{
		vector<int>::iterator it, end=graph[destination].end();
		for(it=graph[destination].begin() ; it!=end ; ++it)
		{
			if(!father[*it] || !emptySpace[*it][destination])
				continue;
			
			father[destination] = *it;
			
			int minFlow = oo;
			for(int node=destination ; node!=source ; node=father[node])
				minFlow = min(minFlow, emptySpace[father[node]][node]);
			
			for(int node=destination ; node!=source ; node=father[node])
			{
				emptySpace[father[node]][node] -= minFlow;
				emptySpace[node][father[node]] += minFlow;
			}
			
			maxFlow += minFlow;
		}
	}
	
	out << maxFlow << '\n';
	
	in.close();
	out.close();
	return 0;
}

bool bfs()
{
	memset(father, 0, sizeof(father));
	father[source] = -1;
	
	queue<int> bfsq;
	bfsq.push(source);
	
	while(!bfsq.empty())
	{
		int current = bfsq.front();
		bfsq.pop();
		
		if(current == destination)
			break;
		
		vector<int>::iterator it, end=graph[current].end();
		for(it=graph[current].begin() ; it!=end ; ++it)
		{
			if(!father[*it] && emptySpace[current][*it])
			{
				father[*it] = current;
				bfsq.push(*it);
			}
		}
	}
	
	return father[destination]? true : false;
}