Cod sursa(job #916445)

Utilizator vlad.maneaVlad Manea vlad.manea Data 16 martie 2013 15:14:02
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;

#define NMAX 1024
#define INFILE "maxflow.in"
#define OUTFILE "maxflow.out"
int ans, N, M;

vector<int> list[NMAX];
int capacities[NMAX][NMAX];
int flows[NMAX][NMAX];

void read()
{
	int x, y, c;
	ifstream fin(INFILE);
	fin >> N >> M;
	
	while (M--)
	{
		fin >> x >> y >> c;
		list[x].push_back(y);
		list[y].push_back(x);
		capacities[x][y] += c;
	}

	fin.close();
}

int traverse()
{
	int ans = 0;
	bool seen[NMAX];
	int papa[NMAX];

	int x, y, f, c, m;
	queue<int> nodes;

	for (int i = 1; i <= N; ++i)
	{
		papa[i] = 0;
		seen[i] = false;
	}

	nodes.push(1);
	seen[1] = true;
	
	while (!nodes.empty())
	{
		x = nodes.front();

		for (int i = 0; i < list[x].size(); ++i) 
		{
			y = list[x][i];

			if (seen[y] == true || y == N)
			{
				continue;
			}

			f = flows[x][y];
			c = capacities[x][y];

			if (f < c)
			{
				seen[y] = true;
				papa[y] = x;
				nodes.push(y);
			}
		}

		nodes.pop();
	}

	for (int i = 0; i < list[N].size(); ++i)
	{
		x = list[N][i];
		f = flows[x][N];
		c = capacities[x][N];

		if (seen[x] == true && f < c)
		{
			m = numeric_limits<int>::max();

			for (y = N; x && m > 0; y = x, x = papa[x])
			{
				m = min(m, capacities[x][y] - flows[x][y]);
			}

			if (m <= 0)
			{
				continue;
			}

			for (y = N, x = list[N][i]; x; y = x, x = papa[x])
			{
				flows[x][y] += m;
				flows[y][x] -= m;
			}

			ans += m;
		}
	}

	return ans;
}

void solve()
{
	int f;

	do
	{
		f = traverse();
		ans += f;
	}
	while (f);
}

void write()
{
	ofstream fout(OUTFILE);
	fout << ans << endl;
	fout.close();
}

int main()
{
	read();
	solve();
	write();
}