Cod sursa(job #306489)

Utilizator SleepyOverlordPatcas Csaba SleepyOverlord Data 20 aprilie 2009 23:06:27
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
//Code by Patcas Csaba
//Time complexity: O(n * m^2)
//Space complexity: O(n^2)
//Method: Edmonds-Karp
//Working time: 35 minutes

#include <cstdio>
#include <vector>
#include <queue>

#define FOR(i,a,b) for (int i=a;i<=b;++i)
#define FORN(i,n) for (int i=0;i<n;++i)
#define inf 2000000000

#define VI vector <int>

using namespace std;

int nTest, n , m, maxFlow, cutSize;

vector <VI> g, g2;
VI father;

void AddEdge(int node1, int node2, int cap)
{
	g[node1][node2]+= cap;
	g2[node1][node2]+= cap;
}

void Bf()
{
	father.clear();
	father.resize(n+1);
	father[1]=-1;
	queue <int> l;
	l.push(1);
	while (!father[n] && !l.empty())
	{
		int node=l.front();
		FOR(i, 1, n)
			if (!father[i] && g2[node][i])
			{
				father[i]=node;
				l.push(i);
			}
		l.pop();
	}
}

int IncreaseFlow()
{
	int flow=inf, node=n;
	while (father[node]!=-1)
	{
		flow=min(flow,g2[father[node]][node]);
		node=father[node];
	}
	node=n;
	while (father[node]!=-1)
	{
		g2[father[node]][node]-=flow;
		g2[node][father[node]]+=flow;
		node=father[node];
	}
	return flow;
}

void Solve()
//Edmonds-Karp
{
	maxFlow= 0;
	while (1)
	{
		Bf();
		if (!father[n]) break;
		FOR(i, 1 ,n)
			if (father[i] && g2[i][n])
			{
				father[n]= i;
				maxFlow+= IncreaseFlow();
			}
	}
	
}

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	
	//scanf("%d", &nTest);
	nTest=1;
	FORN(t, nTest)
	{
		scanf("%d%d", &n, &m);
		g.clear();
		g2.clear();
		g.resize(n+1, VI(n+1));
		g2.resize(n+1, VI(n+1));
		FORN(i, m)
		{
			int x, y, z;
			scanf("%d%d%d", &x, &y, &z);
			AddEdge(x, y, z);
		}

		Solve();

		printf("%d",maxFlow);
	}

	return 0;
}