Cod sursa(job #1770767)

Utilizator TimitocArdelean Andrei Timotei Timitoc Data 4 octombrie 2016 20:21:28
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#define MAXN 15050
#define MAXM 30050

using namespace std;

struct edge
{
    int x, y, c;
    bool operator()(edge a, edge b)
    {
        return a.c < b.c;
    }
};
edge e[MAXM];
int n, m, k;
int w[MAXN], parent[MAXN], d[MAXN], cost[MAXN];

void read()
{
    scanf("%d %d %d", &n, &m, &k);
    for (int i = 1; i <= m; i++)
		scanf("%d %d %d", &e[i].x, &e[i].y, &e[i].c);
	sort(e+1, e+1+m, edge());
}

int getRoot(int x)
{
    if (x == parent[x]) return x;
    return getRoot(parent[x]);
}

int united(int x, int y)
{
	return (getRoot(x) == getRoot(y));
}

void unify(int x, int y, int c)
{
    int px = getRoot(x);
    int py = getRoot(y);
    if (px == py) return ;
    if (w[px] > w[py]) {
        parent[py] = px;
        cost[py] = c;
        w[px] += w[py];
    }
    else {
		parent[px] = py;
		cost[px] = c;
		w[py] += w[px];
    }
}

int getDepth(int nod)
{
    if (d[nod] != 0)
		return d[nod];
	if (nod == parent[nod])
		return (d[nod] = 1);
	d[nod] = getDepth(parent[nod]) + 1;
    return d[nod];
}

void build()
{
	for (int i = 1; i <= n; i++) {
		parent[i] = i;
        w[i] = 1;
	}
    for (int i = 1, crt = 1; crt <= n-1 && i <= m; i++) {
        if (united(e[i].x, e[i].y)) continue;
        crt++;
        unify(e[i].x, e[i].y, e[i].c);
    }
    for (int i = 1; i <= n; i++)
        d[i] = getDepth(i);
}

void solve()
{
    for (int i = 1; i <= k; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
		int maxi = -1;
        while (x != y) {
            if (d[x] < d[y])
				swap(x, y);
            maxi = max(maxi, cost[x]);
            x = parent[x];
        }
        printf("%d\n", maxi);
    }
}

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

    read();
    build();
    solve();

    return 0;
}