Cod sursa(job #2472874)

Utilizator florin_salamFlorin Salam florin_salam Data 13 octombrie 2019 01:35:40
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
//Edmonds-Karp
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

const int NMAX = 1005;
int nodes, edges;
int residual_graph[NMAX][NMAX];
vector <int> graph[NMAX];
int father[NMAX];

bool bfs()
{
	fill(father + 1, father + nodes + 1, 0);
	bitset <NMAX> seen;
	queue <int> q;
	q.push(1);
	seen[1] = 1;
	bool haveAugumentedPath = false;
	while (!q.empty())
	{
		int node = q.front();
		q.pop();
		if (node == nodes)
		{
			haveAugumentedPath = true;
			continue;
		}
		for (auto &next : graph[node])
		{
			if (seen[next] == 0 && residual_graph[node][next] > 0)
			{
				seen[next] = 1;
				father[next] = node;
				q.push(next);
			}
		}
	}
	return haveAugumentedPath;
}

int main()
{
	ifstream fin("maxflow.in");
	ofstream fout("maxflow.out");
	fin >> nodes >> edges;
	for (int i = 1;i <= edges;++i)
	{
		int u, v, c;
		fin >> u >> v >> c;
		graph[u].push_back(v);
		graph[v].push_back(u);
		residual_graph[u][v] += c;
	}
	int maxflow = 0;
	while (bfs())
	{
		for (auto &x : graph[nodes])
		{
			int mn = (1 << 30);
			for (int now = nodes;now != 1;now = father[now])
			{
				int u = father[now];
				int v = now;
				mn = min(mn, residual_graph[u][v]);
			}
			for (int now = nodes;now != 1;now = father[now])
			{
				int u = father[now];
				int v = now;
				residual_graph[u][v] -= mn;
				residual_graph[v][u] += mn;
			}
			maxflow += mn;
		}
	}
	fout << maxflow << "\n";
	fin.close();
	fout.close();
	return 0;
}