Cod sursa(job #895248)

Utilizator fhandreiAndrei Hareza fhandrei Data 27 februarie 2013 10:39:51
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.08 kb
// Include
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

// Definitii
#define mp make_pair
#define pb push_back

#define edge pair<int, pair<int, int> >
#define cost first
#define from second.first
#define to second.second

#define edg pair<int, int>

// Constante
const int sz = (int)15e3+1;

// Functii
int getRoot(int node);
int dfs(int node, int stop, int length);
#define node second

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

bool found;
int nodes, edges, questions;

bool visited[sz];
int root[sz];
int memoize[sz][sz];

vector<edg> graph[sz];
priority_queue< edge, vector<edge>, greater<edge> > heap;

// Main
int main()
{
	in >> nodes >> edges >> questions;
	
	int rFrom, rTo, rCost;
	while(edges--)
	{
		in >> rFrom >> rTo >> rCost;
		heap.push(mp(rCost, mp(rFrom, rTo)));
	}
	
	while(!heap.empty())
	{
		edge current = heap.top();
		heap.pop();
		
		int node1 = current.from;
		int node2 = current.to;
		
		int root1 = getRoot(node1);
		int root2 = getRoot(node2);
		
		if(root1 == root2)
			continue;
		
		root[root2] = root1;
		
		graph[node1].pb(mp(current.cost, node2));
		graph[node2].pb(mp(current.cost, node1));
	}
	
	
	int node1, node2;
	while(questions--)
	{
		memset(visited, false, sizeof(visited));
		in >> node1 >> node2;
		
		found = false;
		out << dfs(node1, node2, 0) << '\n';
	}
	
	
	in.close();
	out.close();
	return 0;
}

#undef node
#undef to
#define to second
int dfs(int node, int stop, int length)
{
	if(memoize[node][stop])
		return max(memoize[node][stop], length);
	
	if(node == stop)
		return length;
	
	visited[node] = true;
	
	vector<edg>::iterator it, end=graph[node].end();
	for(it=graph[node].begin() ; it!=end && !found ; ++it)
		if(!visited[it->to])
		{
			int val = dfs(it->to, stop, it->cost);
			if(val)
			{
				memoize[node][stop] = val;
				return max(val, it->cost);
			}
		}
	
	return 0;
}


int getRoot(int node)
{	return root[node]? root[node]=getRoot(root[node]) : node;	}