Cod sursa(job #1611838)

Utilizator ArkinyStoica Alex Arkiny Data 24 februarie 2016 14:51:27
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include<fstream>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
using namespace std;

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

#define MAX 1010

int N, M, CAP[MAX][MAX], FLOW[MAX][MAX],T[MAX],capacity;

vector<int> G[MAX];
bitset<MAX> vis;

queue<int> Q,Q2;

bool BFS(int S)
{
	Q.push(S);
	vis[S] = 1;
	while (Q.size())
	{
		int node = Q.front();
		if (node == N)
		{
			while (Q.size()) Q.pop();

			return 1;
		}
		for (int i = 0; i < G[node].size(); ++i)
		{
			if (vis[G[node][i]] == 0 && FLOW[node][G[node][i]]>0)
			{
				vis[G[node][i]] = 1;
				T[G[node][i]] = node;
				if (G[node][i] == N)
					Q2.push(node);
				Q.push(G[node][i]);
			}
			else if (G[node][i] == N && FLOW[node][G[node][i]]>0)
				Q2.push(node);
		}
		Q.pop();
	}
	return 0;
}

void EdmondKarp()
{
	while (BFS(1))
	{
		while (Q2.size())
		{
			int node = Q2.front();
			int node1 = node;
			int mn = FLOW[node][N];

			while (node != 1)
			{
				mn = min(mn, FLOW[T[node]][node]);
				node = T[node];
			}

			node = node1;
			FLOW[node][N] -= mn;
			FLOW[N][node] += mn;
			while (node != 1)
			{
				FLOW[T[node]][node] -= mn;
				FLOW[node][T[node]] += mn;
				node = T[node];
			}
			capacity += mn;
			Q2.pop();
		}
		vis.reset();
	}
}


int main()
{
	in >> N >> M;
	for (int i = 1; i <= M; ++i)
	{
		int x, y, c;
		in >> x >> y >> c;
		G[x].push_back(y);
		G[y].push_back(x);
		CAP[x][y] = c;
		FLOW[x][y] = c;
	}
	EdmondKarp();
	out << capacity;
	return 0;
}