Cod sursa(job #8352)

Utilizator MariusMarius Stroe Marius Data 24 ianuarie 2007 17:41:44
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.65 kb
#include <cstdio>
#include <algorithm>
using namespace std;

const char iname[] = "radiatie.in";
const char oname[] = "radiatie.out";

#define MAX_N  15000
#define MAX_M  30000
#define MAX_LG 20

struct edge {
	int x;
	int y;
	int c;
} L[MAX_M];

int Grup[MAX_N], Numara[MAX_N];

int Primul[MAX_N], Ultimul[MAX_N], Link[MAX_N];

int cnt[MAX_N], cost[MAX_N][MAX_LG], grup[MAX_N][MAX_LG];


int compare(edge a, edge b) {
	return (a.c < b.c);
}

void uniq(int x, int y, int c)
{
	int grX = Grup[x];
	int grY = Grup[y];
	if (grX == grY)
		return ;
	if (Numara[grX] > Numara[grY])
		grX ^= grY ^= grX ^= grY;
	for (int i = Primul[grX]; i; i = Link[i]) {
		Grup[i] = grY;
		cnt[i] ++;
		grup[i][ cnt[i] ] = grY;
		cost[i][ cnt[i] ] = c;
	}
	Numara[grY] += Numara[grX];
	Numara[grX]  = 0;
	Link[ Ultimul[grY] ] = Primul[grX];
	Ultimul[grY] = Ultimul[grX];
}

int query(int x, int y)
{
	int i = cnt[x];
	int j = cnt[y];
	for (; grup[x][i] == grup[y][j]; --i, --j) 
		;
	++i, ++j;
	return ((cost[x][i] > cost[y][j]) ? cost[x][i] : cost[y][j]);
}

int main(void) 
{
	freopen(iname, "r", stdin);
	int N;
	int M;
	int K;
	scanf("%d %d %d", & N, & M, & K);
	for (int i = 0; i < M; ++i)
		scanf("%d %d %d", & L[i].x, & L[i].y, & L[i].c);
	sort(L, L + M, compare);
	for (int i = 1; i <= N; ++i) {
		Grup[i] = Primul[i] = Ultimul[i] = i;
		Link[i] = 0;
		Numara[i] = 1;
		cnt[i] = 1;
		grup[i][1] = i;
	}
	for (int i = 0; i < M; ++i)
		uniq(L[i].x, L[i].y, L[i].c);
	freopen(oname, "w", stdout);
	for (int i = 0; i < K; ++i) {
		int x;
		int y;
		scanf("%d %d", & x, & y);
		printf("%d\n", query(x, y));
	}
	return 0;
}