Cod sursa(job #7744)

Utilizator gcosminGheorghe Cosmin gcosmin Data 22 ianuarie 2007 10:25:53
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

#define NMAX 15010
#define LGMAX 17

typedef struct muchie {
	int x, y, c;
};

int N, M, K;

muchie a[2 * NMAX];
int tata[NMAX];

vector <pair <int, int> > leg[NMAX];

int tt[LGMAX][NMAX];
int cc[LGMAX][NMAX];

int cmp(muchie a, muchie b)
{
	return a.c < b.c;
}

int father(int x)
{
	return (tata[x] == x) ? x : tata[x] = father(tata[x]);
}
void unite(int x, int y)
{
	(rand() % 2) ? tata[x] = y : tata[y] = x;
}

char viz[NMAX];
int niv[NMAX];

void df(int x)
{
	viz[x] = 1;

	for (vector <pair<int, int> > :: iterator it = leg[x].begin(); it != leg[x].end(); ++it) 
		if (!viz[(*it).first]) {
			tt[0][(*it).first] = x;
			cc[0][(*it).first] = (*it).second;
			niv[(*it).first] = niv[x] + 1;

			df((*it).first);
		}	
}

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

int main()
{
	int i, j, k, t1, t2;
	
	freopen("radiatie.in", "r", stdin);
	freopen("radiatie.out", "w", stdout);

	scanf("%d %d %d", &N, &M, &K);
 
	for (i = 1; i <= M; i++) scanf("%d %d %d", &a[i].x, &a[i].y, &a[i].c);

	for (i = 1; i <= N; i++) tata[i] = i;

	sort(a + 1, a + M + 1, cmp);

	for (i = 1; i <= M; i++) {
		t1 = father(a[i].x); t2 = father(a[i].y);

		if (t1 != t2) {
			unite(t1, t2);
			leg[a[i].x].push_back(make_pair(a[i].y, a[i].c));
			leg[a[i].y].push_back(make_pair(a[i].x, a[i].c));
		}
	}

	df(1);

	int lg, lgmax;
	for (i = 1, lg = 2; lg <= N; lg <<= 1, i++)
		for (j = 1; j <= N; j++) {
			tt[i][j] = tt[i-1][tt[i-1][j]];
			cc[i][j] = MAX(cc[i-1][j], cc[i-1][tt[i-1][j]]);
		}	
	lgmax = i;

	int x, y;
	for (i = 1; i <= K; i++) {
		scanf("%d %d", &x, &y);

		int c1 = 0, c2 = 0;
		
		for (k = lgmax; k >= 0 && niv[x] > niv[y]; k--)
			if (niv[x] - (1 << k) >= niv[y]) {
				c1 = MAX(c1, cc[k][x]);
				x = tt[k][x];
			}

		for (k = lgmax; k >= 0 && niv[y] > niv[x]; k--)
			if (niv[y] - (1 << k) >= niv[x]) {
				c2 = MAX(c2, cc[k][y]);
				y = tt[k][y];
			}

		for (k = lgmax; k >= 0; k--)
			if (tt[k][x] != tt[k][y]) {
				c1 = MAX(c1, cc[k][x]);
				c2 = MAX(c2, cc[k][y]);
				x = tt[k][x]; y = tt[k][y];
			}

		if (x != y) c1 = MAX(c1, cc[0][x]), c2 = MAX(c2, cc[0][y]);

		printf("%d\n", MAX(c1, c2));		
	}

fclose(stdin);
fclose(stdout);
return 0;
}