Cod sursa(job #560906)

Utilizator Bit_MasterAlexandru-Iancu Caragicu Bit_Master Data 18 martie 2011 19:03:55
Problema Radiatie Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

const int N = 15001;
const int M = 30001;

struct mchie
{
	int a,b,cost;
};

inline int max(int a, int b)
{
	return (a>b)?a:b;
}

int tata[N]; int n;
mchie muchie[M]; int m;
vector<int> vecin[N];
vector<int> cost[N];
int h[N];
bool vizitat[N];
int cost_urcare[N];

int radacina(int x)
{
	int nod,rad,aux;
	nod = x;
	while (tata[nod] != 0)
		nod = tata[nod];
	rad = nod;
	nod = x;
	while (tata[nod] != 0)
	{
		aux = tata[nod];
		tata[nod] = rad;
		nod = aux;
	}
	return rad;
}

bool aceeasi_multime(int x, int y)
{
	return radacina(x) == radacina(y);
}

void reuniune(int x, int y)
{
	tata[radacina(x)] = radacina(y);
}

bool muchii_crescatoare(mchie x, mchie y)
{
	return x.cost <= y.cost;
}

void apm()
{
	sort(muchie+1,muchie+m+1,muchii_crescatoare);
	for (int i = 1; i <= m; ++i)
		if (!aceeasi_multime(muchie[i].a,muchie[i].b))
		{
			vecin[muchie[i].a].push_back(muchie[i].b);
			cost[muchie[i].a].push_back(muchie[i].cost);
			vecin[muchie[i].b].push_back(muchie[i].a);
			cost[muchie[i].b].push_back(muchie[i].cost);
			reuniune(muchie[i].a,muchie[i].b);
		}
}

void dfs(int nod, int adancime)
{
	//refolosim tata pentru un alt scop.
	int dest,cst;
	vizitat[nod] = true;
	h[nod] = adancime;
	for (unsigned int i = 0; i < vecin[nod].size(); ++i)
	{
		dest = vecin[nod][i];
		cst = cost[nod][i];
		if (vizitat[dest])
			continue;
		tata[dest] = nod;
		cost_urcare[dest] = cst;
		dfs(dest,adancime+1);
	}
}

void raspundere(int a, int b)//lca de complexitate cam mare
{
	int cmax = 0;
	while (a != b)
	{
		if (h[a] < h[b])
		{
			cmax = max(cmax,cost_urcare[b]);
			b = tata[b];
		}
		else
		{
			cmax = max(cmax,cost_urcare[a]);
			a = tata[a];
		}
	}
	printf("%d\n",cmax);
}

void citire_si_rezolvare()
{
	int x,y,q;
	scanf("%d%d%d",&n,&m,&q);
	for (int i = 1; i <= m; ++i)
		scanf("%d%d%d",&muchie[i].a,&muchie[i].b,&muchie[i].cost);
	apm();
	tata[1] = 0;
	dfs(1,0);
	for (int i = 1; i <= q; ++i)
	{
		scanf("%d%d",&x,&y);
		raspundere(x,y);
	}
}


int main()
{
	freopen("radiatie.in","r",stdin);
	freopen("radiatie.out","w",stdout);
	citire_si_rezolvare();
	return 0;
}