Cod sursa(job #239892)

Utilizator ilincaSorescu Ilinca ilinca Data 6 ianuarie 2009 03:10:07
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>

#define nmax 1005
#define inf ((unsigned int)1<<31)-1
#define pr(x) fprintf(stderr,#x" = %d\n",x)

using namespace std;

int n, m, pred [nmax], c [nmax] [nmax], f [nmax] [nmax];
char viz [nmax];
vector <int> g [nmax];

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

int BFS ()
{
	int k;
	queue <int> q;
	vector <int>::iterator i;
	memset (viz, 0, sizeof (viz));
	q.push (1);
	viz [1]=1;
	while (!q.empty ())
	{
		k=q.front ();
		for (i=g [k].begin (); i != g [k].end (); ++i)
			if (!viz [*i] && c [k] [*i] > f [k] [*i])
			{
				viz [*i]=1;
				pred [*i]=k;
				q.push (*i);
				if (*i == n)
					return 1;
			}
		q.pop ();
	}
	return 0;
}

int minim_traseu ()
{
	int min=inf, i;
	for (i=n; i != 1; i=pred [i])
		if (min > c [pred [i]] [i]-f [pred [i]] [i])
			min=c [pred [i]] [i]-f [pred [i]] [i];
	return min;
}

void cresc (int v)
{
	int i;
	for (i=n; i != 1; i=pred [i])
	{
		f [pred [i]] [i]+=v;
		f [i] [pred [i]]-=v;
	}
}

int flux ()
{
	int a=0, min;
	while (BFS ())
	{
		min=minim_traseu ();
		cresc (min);
		a+=min;
	}
	return a;
}

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