Cod sursa(job #827267)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 1 decembrie 2012 21:34:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb

#include <cstdio>
#include <cstring>

const int MAX_SIZE(1001);
const int MAX_CAPACITY(110001);

int n, m, source, sink, maxflow;
int capacity [MAX_SIZE] [MAX_SIZE];
int queue [MAX_SIZE], *pop, *push;
int pred [MAX_SIZE];
int augment [MAX_SIZE], *path;

struct edge
{
	int node;
	struct edge *next;
} *graph [MAX_SIZE];

inline void add (int x, int y)
{
	struct edge *new_edge(new struct edge);
	new_edge->node = y;
	new_edge->next = graph[x];
	graph[x] = new_edge;
}

inline void read (void)
{
	std::freopen("maxflow.in","r",stdin);
	std::scanf("%d%d",&n,&m);
	source = 1;
	sink = n;
	int x, y, c;
	for (int counter(0) ; counter < m ; ++counter)
	{
		std::scanf("%d%d%d",&x,&y,&c);
		add(x,y);
		add(y,x);
		capacity[x][y] = c;
	}
	std::fclose(stdin);
}

inline void print (void)
{
	std::freopen("maxflow.out","w",stdout);
	std::printf("%d\n",maxflow);
	std::fclose(stdout);
}

inline void BreadthFirstSearch (void)
{
	std::memset(pred + 1,0,sizeof(*pred) * n);
	pred[source] = -1;
	*queue = source;
	pop = queue;
	push = queue + 1;
	path = augment;
	int vertex;
	struct edge *iterator;
	while (pop < push)
	{
		vertex = *pop;
		++pop;
		for (iterator = graph[vertex] ; iterator ; iterator = iterator->next)
			if (capacity[vertex][iterator->node] && !pred[iterator->node])
			{
				if (iterator->node == sink)
				{
					*path = vertex;
					++path;
					continue;
				}					
				pred[iterator->node] = vertex;
				*push = iterator->node;
				++push;
			}
	}
}

inline void FordFulkerson (void)
{
	int path_capacity, vertex;
	while (true)
	{
		BreadthFirstSearch();
		if (path == augment)
			break;
		--path;
		while (path >= augment)
		{
			pred[sink] = *path;
			path_capacity = MAX_CAPACITY;
			for (vertex = sink ; vertex != source ; vertex = pred[vertex])
				if (capacity[pred[vertex]][vertex] < path_capacity)
					path_capacity = capacity[pred[vertex]][vertex];
			for (vertex = sink ; vertex != source ; vertex = pred[vertex])
			{
				capacity[pred[vertex]][vertex] -= path_capacity;
				capacity[vertex][pred[vertex]] += path_capacity;
			}
			maxflow += path_capacity;
			--path;
		}
	}
}

int main (void)
{
	read();
	FordFulkerson();
	print();
	return 0;
}