Cod sursa(job #708762)

Utilizator AndreiRSStatescu Andrei Rares AndreiRS Data 7 martie 2012 10:08:30
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream fi ("maxflow.in");
ofstream fo ("maxflow.out");

const int nmax = 1005;
int N, M, C[nmax][nmax], F[nmax][nmax], Q[nmax], T[nmax];
vector <int> V[nmax];

void cit ()
{
	fi >> N >> M;
	for (int i = 0, x, y, c; i < M; i++)
	{
		fi >> x >> y >> c;
		
		C[x][y] = c;
		V[x].push_back (y);
		V[y].push_back (x);
	}
	Q[0] = 1;
}

int bf ()
{
	int p = 0, u = 0, ok = 0, n, f;
	for (int i = 1; i <= N; i++)
		T[i] = 0;
	
	while (p <= u)
	{
		n = Q[p];
		for (int i = 0; i < V[n].size(); i++)
		{
			f = V[n][i];
			if (T[f] == 0 && C[n][f] > F[n][f])
			{
				if (f == N)
				{
					ok = 1;
					continue;
				}
				
				Q[++u] = f;
				T[f] = n;
			}
		}		
		p++;
	}
	
	return ok;
}

void rez ()
{
	int i, n, t, m;
	
	while ( bf () )
	{
		for (i = 0; i < V[N].size(); i++)
		{
			if (T[V[N][i]] == 0)
				continue;
			
			n = N;
			t = V[N][i];
			m = C[t][n] - F[t][n];			
			while (t != 1)
			{
				n = t;
				t = T[n];
				m = min (m, C[t][n] - F[t][n]);	
			}
			
			n = N;
			t = V[N][i];
			while (n != 1)
			{
				F[t][n] += m;
				F[n][t] -= m;
				
				n = t;
				t = T[n];
			}			
		}		
	}
}

void afi ()
{
	int s = 0;
	for (int i = 0; i < V[1].size(); i++)
		s += F[1][V[1][i]];
	fo << s << '\n';
}

int main ()
{
	cit ();
	rez ();
	afi ();
	return 0;
}