Cod sursa(job #843277)

Utilizator stoicatheoFlirk Navok stoicatheo Data 27 decembrie 2012 17:58:14
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.75 kb
#include <cstdio>
#include <cstdlib>
#include <algorithm>
 
using namespace std;
 
const int MMAX = 30010;
const int NMAX = 15010;
 
#define Node(a) (*(Latura *)(a))
 
typedef struct { int x, y, c; } Latura;
 
int Comp(const void *a, const void *b);
int Found(int x);
void Union(int x, int y, int Cost);
 
int N, M, T[NMAX], Level[NMAX], d[NMAX], c[NMAX], Q;
Latura Leg[MMAX];
 
int main()
{
    int i, j, max, a, b, aux;
 
    freopen("radiatie.in", "r", stdin);
    freopen("radiatie.out", "w", stdout);
 
    scanf("%d%d%d", &N, &M, &Q);
    for(i = 0; i < M; i++)
        scanf("%d%d%d", &Leg[i].x, &Leg[i].y, &Leg[i].c);
    qsort(Leg, M, sizeof(Latura), Comp);
 
    for(i = 1; i <= N; i++)
    T[i] = i, d[i] = 1;
 
    for (i = 0; i < M; i++)
    {
        if(Found(Leg[i].x) == Found(Leg[i].y)) continue;
        Union(Found(Leg[i].x), Found(Leg[i].y), Leg[i].c);
    }
    for (i = 1; i <= N; i++) Found(i);
 
    for(i = 0; i < Q; i++)
    {
        scanf("%d%d", &a, &b);
        max = 0;
        if ( d[a] < d[b] ) swap(a,b);
         
        for(; d[a] > d[b]; a = T[a])
            max = max < c[a] ? c[a] : max;
        for(; a != b; a = T[a], b = T[b])
            max = max < c[a] ? c[a] : max,
            max = max < c[b] ? c[b] : max;
         
        printf("%d\n", max);
    }
    return 0;
}
 
int Comp(const void *a, const void *b)
{
    return Node(a).c - Node(b).c;
}
 
int Found(int x)
{
    int nr = 0, y;
    y = x;
    for(; x != T[x]; x = T[x], nr++);
    d[y] = nr;
    return x;
}
 
void Union(int x, int y, int Cost)
{
    if(Level[x] <= Level[y])
    {
        T[x] = y, c[x] = Cost;
        if(Level[x] == Level[y])
        Level[y]++;
    }
    else T[y] = x, c[y] = Cost;
}