Cod sursa(job #2471497)

Utilizator florin_salamFlorin Salam florin_salam Data 11 octombrie 2019 01:16:47
Problema Flux maxim Scor 70
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.38 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);
	queue <int> q;
	q.push(1);
	father[1] = -1;
	while (!q.empty())
	{
		int node = q.front();
		q.pop();
		for (auto &next : graph[node])
			if (father[next] == 0 && residual_graph[node][next] > 0)
			{
				father[next] = node;
				q.push(next);
				if (next == nodes)
					return true;
			}
	}
	return false;
}

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())
	{
		int mn = (1 << 30);
		int now = nodes, u, v;
		while (father[now] != -1)
		{
			u = father[now];
			v = now;
			mn = min(mn, residual_graph[u][v]);
			now = father[now];
		}
		now = nodes;
		while (father[now] != -1)
		{
			u = father[now];
			v = now;
			residual_graph[u][v] -= mn;
			residual_graph[v][u] += mn;
			now = father[now];
		}
		maxflow += mn;
	}
	fout << maxflow << "\n";
	fin.close();
	fout.close();
	return 0;
}