Cod sursa(job #899411)

Utilizator fhandreiAndrei Hareza fhandrei Data 28 februarie 2013 14:19:47
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
// Include
#include <fstream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

// Definitii
#define pb push_back

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

// Functii
bool bfs();

// Variabile
ifstream in("maxflow.in");
ofstream out("maxflow.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())
	{
		int minFlow = oo;
		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;
			
			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;
	
	in.close();
	out.close();
	return 0;
}

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