Cod sursa(job #415411)

Utilizator ilincaSorescu Ilinca ilinca Data 11 martie 2010 12:07:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <vector>
#include <queue>

#define nmax 1005
#define inf INT_MAX

using namespace std;

int n, m, s=1, d, pred [nmax], f [nmax] [nmax], c [nmax] [nmax];
vector <int> g [nmax];
bool viz [nmax];


inline int minim (int a, int b)
{
	return (a<b)? a:b;
}

void scan ()
{
	int i, a, b, k;
	scanf ("%d%d", &n, &m);
	d=n;
	for (i=1; i <= m; ++i)
	{
		scanf ("%d%d%d", &a, &b, &k);
		g [a].push_back (b);
		g [b].push_back (a);
		c [a] [b]=k;
	}
}

bool bfs ()
{
	vector <int> :: iterator i;
	queue <int> q;
	int nod;
	memset (viz, 0, sizeof (viz));
	viz [s]=1;
	q.push (s);
	while (!q.empty ())
	{
		nod=q.front ();
	//	fprintf (stderr, "%d\n", nod);
		q.pop ();
		if (nod == d) continue;
		for (i=g [nod].begin (); i != g [nod].end (); ++i)
			if ((c [nod] [*i] > f [nod] [*i]) && (viz [*i] == false || *i == d))
			{
//				printf ("%d %d\n", nod, *i);
				viz [*i]=true;
				pred [*i]=nod;
				q.push (*i);
			}
	}
	return viz [d];
}

int flux ()
{
	int min, nod, flow;
	vector <int> :: iterator i;
	for (flow=0; bfs ();)
		for (i=g [d].begin (); i != g [d].end (); ++i)
		{
			min=inf;
			if (c [*i] [d] == f [*i] [d] || !viz [*i]) continue;
			pred [d]=*i;
			for (nod=d; nod != s; nod=pred [nod])	min=minim (min, c [pred [nod]] [nod]-f [pred [nod]] [nod]); 	
			if (min == 0) continue;
			for (nod=d; nod != s; nod=pred [nod])
			{
				f [pred [nod]] [nod] += min;
				f [nod] [pred [nod]] -= min;
			}
			flow += min;
		}
	return flow;
}

int main ()
{
	freopen ("maxflow.in", "r", stdin);
	freopen ("maxflow.out", "w", stdout);
	scan ();
	printf ("%d\n", flux ());
	return 0;
}