Cod sursa(job #2781493)

Utilizator cezar_titianuTitianu Cezar cezar_titianu Data 9 octombrie 2021 17:40:39
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <cmath>
#include <vector>
#include <queue>
#include <map>

struct edge {
	int flowm, flowc;
};

struct node {
	int par = 0;
	bool viz = false;
	std::map <int, edge> con;
};

struct nodeval {
	int pos;
	int flow;
};

std::vector <node> graph;

int main() {
	std::ifstream fin("maxflow.in");
	std::ofstream fout("maxflow.out");
	std::queue <nodeval> next;
	int nrn, nrm, pos1, pos2, siz;
	nodeval cur;
	int pos, flow;
	int ans;
	fin >> nrn >> nrm;
	graph.resize(nrn);
	for (int index = 0; index < nrm; index++) {
		fin >> pos1 >> pos2 >> siz;
		pos1--;
		pos2--;
		graph[pos1].con[pos2] = { siz, 0 };
		if (graph[pos2].con.find(pos1) == graph[pos2].con.end()) {
			graph[pos2].con[pos1] = { 0, 0 };
		}
	}
	ans = 0;
	graph[0].viz = true;
	while (1) {
		next.push({ 0, 0x7fffffff });
		flow = 0;
		for (int index = 1; index < nrn; index++) {
			graph[index].viz = false;
		}
		while (!next.empty()) {
			cur = next.front();
			next.pop();
			for (std::map <int, edge>::iterator chd = graph[cur.pos].con.begin(); chd != graph[cur.pos].con.end(); chd++) {
				if (chd->second.flowc < chd->second.flowm && !graph[chd->first].viz) {
					graph[chd->first].viz = true;
					graph[chd->first].par = cur.pos;
					next.push({ chd->first, std::min(chd->second.flowm - chd->second.flowc, cur.flow) });
					if (chd->first == nrn - 1) {
						flow = next.back().flow;
						break;
					}
				}
			}
			if (flow) {
				break;
			}
		}
		while (!next.empty()) {
			next.pop();
		}
		if (!flow) {
			break;
		}
		ans += flow;
		pos = nrn - 1;
		while (pos != 0) {
			graph[pos].con[graph[pos].par].flowc -= flow;
			graph[graph[pos].par].con[pos].flowc += flow;
			pos = graph[pos].par;
		}
	}
	fout << ans;
}