Cod sursa(job #300438)

Utilizator peanutzAndrei Homorodean peanutz Data 7 aprilie 2009 14:01:08
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#include <vector>
#include <queue>

using namespace std;

inline int MIN(int a, int b)
{
	if(a > b)
		return b;
	return a;
}

#define NMAX 1004
#define INFI 0x3f3f3f3f

int c[NMAX][NMAX];
int n, m;
vector<int> g[NMAX];
int source, sink;

void read()
{
	int x, y, z;
	scanf("%d %d", &n, &m);
	for(int 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);
	}
	source = 1;
	sink = n;
}

short uz[NMAX];
int t[NMAX];

int bf()
{
	queue<int> q;
	q.push(source);
	memset(uz, 0, sizeof(uz));
	while(!q.empty())
	{
		int crt = q.front();
		q.pop();
		for(vector<int> :: iterator it = g[crt].begin(); it != g[crt].end(); ++it)
		{
			if(!uz[*it] && c[crt][*it])
			{
				++uz[*it];
				t[*it] = crt;
				q.push(*it);
			}
			if(uz[sink])
				return 1;
		}
	}
	return 0;
}

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	
	read();

	int flow = 0, _min, it;
	while(bf())
	{
		for(_min = INFI, it = sink; it != source; it = t[it])
			_min = MIN(_min, c[ t[it] ][it]);
		
		for(it = sink; it != source; it = t[it])
			c[ t[it] ][it] -= _min, c[it][ t[it] ] += _min;
		flow += _min;
	}
	printf("%d\n", flow);
	
	return 0;
}