Cod sursa(job #751406)

Utilizator luckyme91wiz kid luckyme91 Data 26 mai 2012 00:45:05
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;
typedef struct {
	int v;
	map <int, int> n;
} node;
vector <int> parent;
vector <node> nodes;
vector <int> ng;
vector <int> minim;
int n, m;
bool bfs ()
{
	int u;
	queue <int> queue;
	parent.assign(n,-1);
	queue.push(1);
	minim.assign (n, 10000);
	bool ok = false;
	while (!queue.empty())
	{
		u = queue.front();
		queue.pop();
		for (map<int,int>::iterator it = nodes[u].n.begin(); it != nodes[u].n.end(); it++)
		{
			if ((*it).second != 0 && (*it).first != n && parent [(*it).first] == -1)
			{
				minim [(*it).first] = min (minim[u], (*it).second);
				parent[(*it).first] = u;
				queue.push((*it).first);
			}
			if ((*it).first == n)
				ok = true;
		}
	}
	return ok;
}
int maxflow ()
{
	int flow = 0, f, s;
	bool ok;
	while (bfs())
	{
		f = 0;
		for (int i = 0; i < ng.size(); i++)
		{
			if (nodes[ng[i]].n[n] > 0)
			{
				f = min (nodes[ng[i]].n[n], minim[ng[i]]);
				flow += f;
				nodes[ng[i]].n[n] -= f;
				s = ng[i];
				//cout << "drum " <<f << endl;
				while (s != 1)
				{
					nodes[parent[s]].n[s] -= f;
				//	cout << s << " ";
					s = parent[s];

				}
				//cout << endl;
			}
		}
	}
	return flow;
}

int main ()
{
	ifstream in ("maxflow.in", ifstream::in);
	ofstream out ("maxflow.out", ofstream::out);
	
	in >> n >> m;
	int x, y, c;
	nodes.resize(n);
	for (int i = 0; i < m ; i++)
	{
		in >> x >> y >> c;
		nodes[x].n.insert (pair <int, int> (y,c));
		if (y == n)
			ng.push_back(x);
	}
	
	out << maxflow();
	return 0;
}