Cod sursa(job #1354816)

Utilizator anaid96Nasue Diana anaid96 Data 22 februarie 2015 00:36:57
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<queue>
#include<string.h>

using namespace std;

FILE *in, *out;

//definitions
#define pb push_back
#define source 1

//constants
const int sz = (int) 1e3+1;
const int oo = (1<<30)-1;

//variables
int dest, edges;
int from, to, capacity;

vector<int> graph[sz];

int emptySpace[sz][sz];

int tata[sz];
int minflow, maxflow;

//functions
bool bfs();

int main(void)
{
	in = fopen("maxflow.in", "rt");
	out = fopen("maxflow.out", "wt");
	
	fscanf(in, "%d%d", &dest, &edges);
	
	while(edges--)
	{
		fscanf(in, "%d%d%d", &from, &to, &capacity);
		graph[from].pb(to);
		graph[to].pb(from);
		emptySpace[from][to] = capacity;
	}
	
	while(bfs())
	{
		vector<int> :: iterator it, end = graph[dest].end();
		for( it=graph[dest].begin(); it!=end; ++it)
		{
			
			if( !tata[*it] || !emptySpace[*it][dest])
				continue;
			
			tata[dest] = *it;
			minflow = oo;
			
			for(int node=dest; node!=source; node=tata[node])
				minflow = min(minflow, emptySpace[tata[node]][node]);
			
			for(int node=dest; node!=source; node=tata[node])
			{
				emptySpace[tata[node]][node]-=minflow;
				emptySpace[node][tata[node]]+=minflow;
			}
			
			maxflow+=minflow;
			
		}
		
	}
	
	fprintf(out, "%d\n", maxflow);
	
	fclose(in);
	fclose(out);
	return 0;
}

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