Cod sursa(job #974290)

Utilizator hiticas_abelhiticasabel hiticas_abel Data 16 iulie 2013 18:55:24
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.01 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <utility>
#include <string.h>

using namespace std;

ifstream cin("radiatie.in");
ofstream cout("radiatie.out");

const int MAXN = 30005;
const int oo = (1<<31)-1;

struct Edge{
    int x, y, c;
}A[MAXN];

int N, M, K, Father[MAXN>>1] , Level[MAXN>>1], c[MAXN>>1];

struct ClassComp{
    inline bool operator () (const Edge &a, const Edge &b) const{
        return a.c < b.c;
    }
};

inline int find (int x){
    int r = x;
    while(r != Father[r])
        r = Father[r];
    return r;
}

const void findLevel(int x){
    if(Father[x] == x)
        return;
    findLevel(Father[x]);
    Level[x] = Level[Father[x]] + 1;
}

const void ReadInput(){
    cin >> N >> M >> K;
    for(int i = 1 ; i <= M ; ++ i)
        cin >> A[i].x >> A[i].y >> A[i].c;
}

const void BuildApm(){
    sort(A+1, A+M+1 , ClassComp());
    for(int i = 1 ; i <= N ; ++ i)
        Father[i] = i;
    int Num = 0;
    for(int i = 1 ; i <= M && Num < N ; ++ i){
        int Tx = find(A[i].x);
        int Ty = find(A[i].y);
        if( Tx != Ty ){
            Father[Tx] = Ty;
            c[Tx] = A[i].c;
            ++ Num;
        }
    }
    for(int i = 1 ; i <= N ; ++ i)
        if(!Level[i])
            findLevel(i);
}

const void HandleQueries(){
    for(int i = 1 ; i <= K ; ++ i){
        int x, y, MAX = 0;
        cin >> x >> y;
        while(Level[x] > Level[y]){
            MAX = max(MAX, c[x]);
            x = Father[x];
        }
        while(Level[x] < Level[y]){
            MAX = max(MAX, c[y]);
            y = Father[y];
        }
        while(x != y){ /// LCA-ul neoptim, simplu, sper sa intre
            MAX = max(MAX, max(c[x], c[y]));
            x = Father[x];
            y = Father[y];
        }
        cout << MAX << "\n";
    }
}

int main()
{
    ReadInput();
    BuildApm();
    HandleQueries();
    cin.close();
    cout.close();
    return 0;
}