Cod sursa(job #470436)

Utilizator darrenRares Buhai darren Data 13 iulie 2010 19:47:13
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstring>
#include <fstream>
#include <algorithm>
#include <queue>

using namespace std;

const int INF = 1LL << 31 - 1;
const int SIZE = 1001;

bool bfs();
void dim();

int n, m, maxflow;
int c[SIZE][SIZE], f[SIZE][SIZE], cr[SIZE], t[SIZE];
bool s[SIZE];

int main()
{
	ifstream fin("maxflow.in");
	ofstream fout("maxflow.out");
	
	fin >> n >> m;
	for (int i = 1, nod1, nod2, cap; i <= m;  ++i)
	{
		fin >> nod1 >> nod2 >> cap;
		c[nod1][nod2] = cap;
	}
	
	while (bfs())
		dim();
	
	fout << maxflow;
}

bool bfs()
{
	queue<int> q;
	
	memset(cr, 0, sizeof(cr));
	memset(t, 0, sizeof(t));
	memset(s, 0, sizeof(s));
	
	q.push(1);
	cr[1] = INF, s[1] = true;
	
	while (!q.empty())
	{
		int i = q.front(); q.pop();
		for (int j = 1; j <= n; ++j)
			if (!s[j])
				if (f[i][j] < c[i][j])
				{
					cr[j] = min(cr[i], c[i][j] - f[i][j]);
					t[j] = i, s[j] = true;
					q.push(j);
					
					if (j == n) return true;
				}
	}
	
	return false;
}

void dim()
{
	int j = n, i = n;
	while (j != 1)
	{
		i = t[j];
		f[i][j] += cr[n];
		f[j][i] -= cr[n];
		j = i;
	}
	
	maxflow += cr[n];
}