Cod sursa(job #2750093)

Utilizator andrei42Oandrei42O andrei42O Data 9 mai 2021 22:37:59
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;

const int NMAX = 1010;
const int INF = 1000000000;

vector<vector<int>> c;
vector<vector<int>> flow;
int *currentPathCapacity;
int* parent; // parcurgere inversa 
vector <int> *v;
int V, E;

void allocateMemory(int MAXV) {
	for (int i = 1; i <= MAXV + 5; i++) {
		c.push_back(vector<int>(MAXV + 5, 0));
		flow.push_back(vector<int>(MAXV + 5, 0));
	}
	v = new vector<int>[MAXV + 5];
	parent = new int[MAXV + 5];
	currentPathCapacity = new int[MAXV + 5];
		
}

int BFS() {
	queue <int> q;
	q.push(1);
	memset(parent, -1, (V + 5) * sizeof(int)); // reinitializam lista parcursa cu -1
	parent[1] = -2;
	currentPathCapacity[1] = INF;
	while (!q.empty()) {
		int nod = q.front();
		q.pop();
		for (auto it : v[nod]) {
			if (parent[it] == -1) {
				if (c[nod][it] - flow[nod][it] > 0) {
					parent[it] = nod;
					currentPathCapacity[it] = min(currentPathCapacity[nod], c[nod][it] - flow[nod][it]);
					if (it == V) 
						return currentPathCapacity[it];
					q.push(it);
				}
			}
		}

	}
	return 0; // no more flow to pass :(
}

void updateFlow(int tempFlow) {
	int currentNode = V;
	while (currentNode != 1) {
		int previousNode = parent[currentNode];
		flow[previousNode][currentNode] += tempFlow;
		flow[currentNode][previousNode] -= tempFlow;
		currentNode = previousNode;
	}
}

int edmondsKarp() {
	int maxFlow = 0;
	while (true) {
		int tempFlow = BFS();
		if (!tempFlow)
			break;
		maxFlow += tempFlow;
		updateFlow(tempFlow);
	}
	return maxFlow;
}

void deallocateMemory() {
	delete currentPathCapacity;
	delete parent;
}
int main(int argc, char** argv) {
	if (argc != 3) {
		perror("Insufficient arguments passed!\n");
		exit(1);
	}
	ifstream f("maxflow.in");
	ofstream g("maxflow.out");
	f >> V >> E;
	allocateMemory(V);
	for (int x, y, cst; E; E--) {
		f >> x >> y >> cst;
		c[x][y] = cst;
		v[x].push_back(y);
		v[y].push_back(x);
	}
	f.close();
	g << edmondsKarp();
	g.close();
	deallocateMemory();
	return 0;
}