Cod sursa(job #2472850)

Utilizator florin_salamFlorin Salam florin_salam Data 13 octombrie 2019 00:43:44
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 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];
vector <int> augumented_path;

bool bfs()
{
	bitset <NMAX> seen;
	vector <int> dist(nodes + 1, 0);
	augumented_path.clear();
	vector <int> father(nodes + 1, 0);
	queue < pair <int, int> > q;
	q.push(make_pair(1, (1 << 30)));
	seen[1] = 1;
	while (!q.empty())
	{
		int node = q.front().first;
		int cost = q.front().second;
		q.pop();
		for (auto &next : graph[node])
		{
			int newcost = min(cost, residual_graph[node][next]);
			if (seen[next] == 0 && residual_graph[node][next] > 0 && dist[next] < newcost)
			{
				seen[next] = 1;
				dist[next] = newcost;
				q.push(make_pair(next, newcost));
				father[next] = node;
			}
		}
	}
	if (father[nodes] == 0)
		return false;
	int now = nodes;
	while (now != 0)
	{
		augumented_path.push_back(now);
		now = father[now];
	}
	reverse(augumented_path.begin(), augumented_path.end());
	return true;
}

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);
		for (int i = 0;i + 1 < augumented_path.size();++i)
		{
			int u = augumented_path[i];
			int v = augumented_path[i + 1];
			mn = min(mn, residual_graph[u][v]);
		}
		for (int i = 0;i + 1 < augumented_path.size();++i)
		{
			int u = augumented_path[i];
			int v = augumented_path[i + 1];
			residual_graph[u][v] -= mn;
			residual_graph[v][u] += mn;
		}
		maxflow += mn;
	}
	fout << maxflow << "\n";
	fin.close();
	fout.close();
	return 0;
}