Cod sursa(job #1564101)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 8 ianuarie 2016 13:29:00
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <vector>
#include <queue>

#define NMax 1010

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int nodes, edges, cap[NMax][NMax], flow[NMax][NMax], father[NMax], maxFlow;
bool mark[NMax];
vector<int> G[NMax];
queue<int> QU;

void clearQueue(queue<int> q)
{
	queue<int> empty;
	swap(q, empty);
}

int available(int n1, int n2)
{
	return cap[n1][n2] - flow[n1][n2];
}

int getMin(int a, int b)
{
	if (a < b)
		return a;
	return b;
}

bool BFS(int node)
{
	memset(father, 0, sizeof(father));
	memset(mark, 0, sizeof(mark));
	clearQueue(QU);

	QU.push(node);
	mark[node] = true;

	while (!QU.empty()) {
		int crtNode = QU.front();
		QU.pop();

		for (vector<int>::iterator it = G[crtNode].begin(); it != G[crtNode].end(); it++) {
			if (!mark[*it] && available(crtNode, *it) > 0) {
				QU.push(*it);

				father[*it] = crtNode;
				mark[*it] = true;
			}
		}
	}

	if (mark[nodes])
		return true;
	return false;
}

int main()
{
	f >> nodes >> edges;
	
	int n1, n2, c;
	for (int i = 1; i <= edges; i++) {
		f >> n1 >> n2 >> c;

		G[n1].push_back(n2);
		G[n2].push_back(n1);

		cap[n1][n2] = c;
	}

	while (BFS(1)) {
		for (vector<int>::iterator it = G[nodes].begin(); it != G[nodes].end(); it++) {
			if (available(*it, nodes)) {
				int crtNode = 0, crtFlow = available(*it, nodes);

				crtNode = *it;
				while (father[crtNode] > 0) {
					crtFlow = getMin(crtFlow, available(father[crtNode], crtNode));
					crtNode = father[crtNode];
				}

				flow[*it][nodes] += crtFlow;
				flow[nodes][*it] -= crtFlow;

				crtNode = *it;
				while (father[crtNode] > 0) {
					flow[father[crtNode]][crtNode] += crtFlow;
					flow[crtNode][father[crtNode]] -= crtFlow;

					crtNode = father[crtNode];
				}

				maxFlow += crtFlow;
			}
		}
	}

	g << maxFlow;

	return 0;
}