Cod sursa(job #932522)

Utilizator razvan.popaPopa Razvan razvan.popa Data 28 martie 2013 23:42:17
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.49 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], T[nMax], TC[nMax], R[nMax];

int H,  P[nMax], PC[nMax], L[nMax];

list < pii > v[nMax];

int N, M, K;



inline int Find(int x){
	int r;
	for(r = x; TT[r] != r; r = TT[r]);
	return r;
}

inline void addEdge(int x, int y, int c){
	v[x].pb(mkp(y,c));

	T[y] = x;
	TC[y] = c;
}

inline void Union(const edge &e){
	int x = Find(e.x), y = Find(e.y);

	if(R[x] < R[y]){
		TT[x] = y;
		addEdge(e.y, e.x, e.cost);
	}
	else{
		TT[y] = x;
		addEdge(e.x, e.y, e.cost);
	}

	if(R[x] == R[y])
		R[x] ++;
}

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, R[i] = 1;

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

		Union(Edges[i]);
		dimArb ++;

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

	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;
}