Cod sursa(job #932513)

Utilizator razvan.popaPopa Razvan razvan.popa Data 28 martie 2013 23:29:02
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.34 kb
#include<cstdio>
#include<cmath>
#include<list>
#include<algorithm>
#define INF (1 << 30)
#define pb push_back
#define mkp make_pair
#define pii pair<int, int>
#define nxt (*it).first
#define cst (*it).second
#define FOR(i,a,b)\
   for(int i=a; i<=b; ++i)
#define ALL(g)\
   for(typeof(g.begin()) it=g.begin(); it!=g.end(); ++it)
#define infile "radiatie.in"
#define outfile "radiatie.out"
#define nMax 15005
#define mMax 30005
using namespace std;

struct edge{
	int cost, x, y;
	bool operator < (const edge &that)const{
		return cost < that.cost;
	}
} Edges[mMax];

int TT[nMax]; // multimi disjuncte

int H, T[nMax], TC[nMax], P[nMax], PC[nMax], L[nMax]; // lca

list < pii > v[nMax];

int N, M, K;



inline int Find(int x){
	int r, y;
	for(r = x; TT[r] != r; r = TT[r]);

	while(x != TT[x]){
		y = TT[x];
		TT[x] = r;
		x = y;
	}

	return r;
}

void DFS(int x){
	L[x] = L[T[x]] + 1;

	H = max(H, L[x]);

	ALL(v[x])
	   DFS(nxt);
}

void DF(int x, int Up, int costUp){
	P[x] = Up;
	PC[x] = costUp;

	if(L[x] % H == 1)
		Up = x, costUp = 0;

	ALL(v[x])
	   DF(nxt, Up, max(costUp, cst));
}

void process(){
	sort(Edges + 1, Edges + M + 1);

	FOR(i,1,N)
	   TT[i] = i;

	int Rad;
	for(int i = 1, dimArb = -1; i <= M && dimArb < N; ++ i){
		int m1 = Find(Edges[i].x);
		int m2 = Find(Edges[i].y);

		if(m1 == m2)
			continue;

		v[Edges[i].x].pb(mkp(Edges[i].y, Edges[i].cost));

		T[Edges[i].y] = Edges[i].x;
		TC[Edges[i].y] = Edges[i].cost;

		if(!T[Edges[i].x])
			Rad = Edges[i].x;

		TT[m2] = m1;
		dimArb ++;
	}

	DFS(Rad);

	H = (int) sqrt((double)H) + 1;

	DF(Rad, Rad, 0);
}

int lca(int x, int y){
	int cmax = 0;
	while(P[x] != P[y])
		if(L[x] > L[y]){
			cmax = max(cmax, PC[x]);
			x = P[x];
		}
		else{
			cmax = max(cmax, PC[y]);
			y = P[y];
		}

	while(x != y)
		if(L[x] > L[y]){
			cmax = max(cmax, TC[x]);
			x = T[x];
		}
		else{
			cmax = max(cmax, TC[y]);
			y = T[y];
		}

	return cmax;
}


int main(){
	freopen(infile, "r", stdin);
	freopen(outfile, "w", stdout);

	scanf("%d %d %d", &N, &M, &K);

	FOR(i,1,M)
		scanf("%d %d %d", &Edges[i].x, &Edges[i].y, &Edges[i].cost);

	process();

	int x, y;
	while(K--){
		scanf("%d %d", &x, &y);

		printf("%d\n", lca(x,y));
	}

	fclose(stdin);
	fclose(stdout);

    return 0;
}