Cod sursa(job #677636)

Utilizator feelshiftFeelshift feelshift Data 10 februarie 2012 14:23:12
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.63 kb
// http://infoarena.ro/problema/radiatie
#include <fstream>
#include <cstring>
#include <set>
using namespace std;

const int oo = 0x3f3f3f3f;
const int MAXSIZE = 15001;

struct stuff { int from,to,cost; };

class comparison {
	public:
		bool operator() (stuff first,stuff second) {
			return (first.cost < second.cost);
		}
};

ifstream in("radiatie.in");
ofstream out("radiatie.out");

int nodes,edges,voyages;
int treeRank[MAXSIZE];
int maxLength[MAXSIZE];
pair<int,int> father[MAXSIZE];
set<stuff,comparison> edgesSet;

void unite(stuff edge);
int find(int node);

int main() {
	in >> nodes >> edges >> voyages;

	for(int i=1;i<=edges;i++) {
		stuff edge;
		in >> edge.from >> edge.to >> edge.cost;
		edgesSet.insert(edge);
	}

	set<stuff,comparison>::iterator end = edgesSet.end();
	for(set<stuff,comparison>::iterator it=edgesSet.begin();it!=end;++it)
		if(find(it->from) != find(it->to))
			unite(*it);

	int from,to;
	for(int i=1;i<=voyages;i++) {
		in >> from >> to;
		memset(maxLength,0,MAXSIZE*sizeof(int));

		int son = from;
		bool found = false;
		for(;father[from].first;from=father[from].first) {
			maxLength[father[from].first] = max(maxLength[father[son].first],father[from].second);
			if(father[from].first == to) {
				out << maxLength[father[from].first] << "\n";
				found = true;
				break;
			}
			son = from;
		}

		son = to;
		if(!found)
			for(;father[to].first;to=father[to].first) {
				if(maxLength[father[to].first]) {
					out << max(maxLength[father[to].first],maxLength[father[son].first]) << "\n";
					found = true;
					break;
				}

				maxLength[father[to].first] = max(maxLength[father[son].first],father[to].second);
				son = to;
			}

		if(!found)
			out << "Nu am gasit solutie!\n";
	}

	return (0);
}

void unite(stuff edge) {
	int fromRoot = find(edge.from);
	int toRoot = find(edge.to);

	//for(int i=1;i<=nodes;i++)
	//	out << father[i].second << " ";
	//out << "\n";

	//out << "Edge: " << edge.from <<  " " << edge.to << " | ";
	if(treeRank[fromRoot] < treeRank[toRoot]) {
		//father[fromRoot] = toRoot;
		father[edge.from].first = edge.to;
		father[edge.from].second = edge.cost;
		//out << edge.from << "->" << edge.to << " (" << edge.cost << ")\n\n";
	}
	else {
		//father[toRoot] = fromRoot;
		father[edge.to].first = edge.from;
		father[edge.to].second = edge.cost;
		//out << edge.to << "->" << edge.from << " (" << edge.cost << ")\n\n";
	}

	if(treeRank[fromRoot] == treeRank[toRoot])
		treeRank[fromRoot]++;
}

int find(int node) {
	if(!father[node].first)
		return node;
	else
		return find(father[node].first);
}