Cod sursa(job #863933)

Utilizator fhandreiAndrei Hareza fhandrei Data 24 ianuarie 2013 13:36:39
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
// Include
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

// Definitii
#define pb push_back

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

// Functii
bool bfs();

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

int destination, edges;
int minFlow, maxFlow;
int father[sz];
int capacity[sz][sz], currentFlow[sz][sz];

bool visited[sz];

vector<int> graph[sz];

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

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