Cod sursa(job #1454570)

Utilizator starduststardust stardust Data 26 iunie 2015 21:40:15
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define maxn 1030
#define inf 1<<30

using namespace std;


int n, m;
bool viz[maxn];
int parent[maxn];
vector< int > graph[maxn];

int cost[maxn][maxn];
int residualGraph[maxn][maxn];


int min(int a, int b)
{
	if (a < b)
		return a;
	return b;
}

bool bfs()
{
	memset(viz, 0, sizeof(viz));
	queue<int> q;

	q.push(1);
	viz[1] = true;

	while (!q.empty())
	{
		int nod = q.front();
		q.pop();

		if (nod == n)
			continue;
		for (int i = 0; i <  graph[nod].size(); i++)
		{
			int v = graph[nod][i];

			if (!viz[v] && residualGraph[nod][v] != cost[nod][v])
			{
				q.push(v);
				parent[v] = nod;
				viz[v] = true;
			}
		}
	}
	return viz[n];
}

int edmondsKarp()
{
	int max_flow = 0;

	while (true)
	{
		//caut o cale nesaturata
		if (!bfs())
			break;

		for (int i = 0; i < graph[n].size(); i++)
		{
			int nod = graph[n][i];
			if (cost[nod][n] == residualGraph[nod][n] || !viz[nod])
				continue;

			parent[n] = nod;
			int path_flow = inf;

			//gasesc minimul de pe aceasta cale
			for (int v = n; v != 1; v = parent[v])
			{
				int u = parent[v];
				path_flow = min(path_flow, cost[u][v] - residualGraph[u][v]);
			}

			if (path_flow == 0)
				continue;

			for (int v = n; v != 1; v = parent[v])
			{
				int u = parent[v];
				residualGraph[u][v] += path_flow;
				residualGraph[v][u] -= path_flow;
			}

			max_flow += path_flow;
		}
	}

	return max_flow;
}

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	scanf("%d %d", &n, &m);

	int x, y, z;

	for (int i = 0; i < m; i++)
	{
		scanf("%d %d %d", &x, &y, &z);
		graph[x].push_back(y);
		graph[y].push_back(x);
		cost[x][y] = z;
	}

	printf("%d", edmondsKarp());
}