Cod sursa(job #220774)

Utilizator raduzerRadu Zernoveanu raduzer Data 12 noiembrie 2008 18:34:55
Problema Radiatie Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.28 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

const int MAX_M = 30010;
const int MAX_N = 15010;
const int SIZE = 16;

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

struct muchie {
	int nod1, nod2, cost;
};

int n, m, k;
muchie a[MAX_M];
vector <int> v[MAX_N], c[MAX_N];
char f[MAX_N];
int p[MAX_N][SIZE], cost[MAX_N][SIZE];
int nivel[MAX_N], t[MAX_N];

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

int find_dad(int nod)
{
	if (!t[nod]) return nod;
	return t[nod] = find_dad(t[nod]);
}

void attach(int nod1, int nod2)
{
	if (rand() % 2) t[nod1] = nod2;
	else t[nod2] = nod1;
}

void df(int x)
{
	int i, j, nod; 
	f[x] = 1;

	for (j = 1, nod = p[x][0]; nod; nod = p[nod][j - 1], ++j)
	{
		if (p[nod][j - 1])
		{
			p[x][j] = p[nod][j - 1];
			cost[x][j] = max(cost[x][j - 1], cost[nod][j - 1]);
		}
	}

	for (i = 0; i < v[x].size(); ++i)
	{
		nod = v[x][i];
		if (!f[nod])
		{
			p[nod][0] = x;
			cost[nod][0] = c[x][i];
			nivel[nod] = nivel[x] + 1;

			df(nod);
		}
	}
}

void LCA(int x, int y)
{
	int i, sol = -0x3f3f3f3f, bit = 1 << 15;

	if (nivel[x] < nivel[y]) x ^= y ^= x ^= y;

	int val = nivel[x] - nivel[y];
	for (i = SIZE - 1; i >= 0; --i, bit >>= 1)
		if (val & bit)
		{
			sol = max(sol, cost[x][i]);
			x = p[x][i];
		}

	for (i = SIZE - 1; i >= 0; --i)
		if (p[x][i] != p[y][i])
		{
			sol = max(sol, cost[x][i]);
			sol = max(sol, cost[y][i]);

			x = p[x][i];
			y = p[y][i];
		}

	if (x != y) sol = max(sol, max(p[x][0], p[y][0]));
	printf("%d\n", sol);
}

int main()
{
	int i, x, y;
	freopen("radiatie.in", "r", stdin);
	freopen("radiatie.out", "w", stdout);

	scanf("%d %d %d", &n, &m, &k);
	for (i = 0; i < m; ++i) scanf("%d %d %d", &a[i].nod1, &a[i].nod2, &a[i].cost);

	sort(a, a + m, cmp);

	for (i = 0; i < m; ++i)
		if (find_dad(a[i].nod1) != find_dad(a[i].nod2)) 
		{
			attach(t[a[i].nod1], t[a[i].nod2]);

			v[a[i].nod1].push_back(a[i].nod2);
			c[a[i].nod1].push_back(a[i].cost);

			v[a[i].nod2].push_back(a[i].nod1);
			c[a[i].nod2].push_back(a[i].cost);
		}

	for (i = 1; i <= n; ++i) p[i][0] = t[i];

	for (i = 1; i <= n; ++i) 
		if (!f[i]) df(i);

	for (i = 1; i <= k; ++i)
	{
		scanf("%d %d", &x, &y);
		LCA(x, y);
	}
}