Cod sursa(job #827064)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 1 decembrie 2012 16:23:48
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb

#include <cstdio>
#include <cstring>

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

int n, m, source, sink, maxflow;

int capacity [MAX_SIZE] [MAX_SIZE];
int queue [MAX_SIZE], *push, *pop;
int pred [MAX_SIZE];

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

inline void add (int x, int y)
{
	struct edge *new_edge(new struct edge);
	new_edge->vertex = 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 int BreadthFirstSearch (void)
{
	std::memset(pred + 1,0,sizeof(*pred) * n);
	pred[source] = -1;
	*queue = source;
	pop = queue;
	push = queue + 1;
	int vertex;
	struct edge *iterator;
	while (pop < push)
	{
		vertex = *pop;
		++pop;
		for (iterator = graph[vertex] ; iterator ; iterator = iterator->next)
		{
			if (!capacity[vertex][iterator->vertex] || pred[iterator->vertex])
				continue;
			pred[iterator->vertex] = vertex;
			if (iterator->vertex == sink)
				goto Skip;
			*push = iterator->vertex;
			++push;
		}
	}
	if (!pred[sink])
		return 0;
	Skip :
	int 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;
	}
	return path_capacity;
}

inline void FordFulkerson (void)
{
	int path_capacity;
	while (true)
	{
		path_capacity = BreadthFirstSearch();
		if (!path_capacity)
			break;
		maxflow += path_capacity;
	}
}

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