Cod sursa(job #932851)

Utilizator razvan.popaPopa Razvan razvan.popa Data 29 martie 2013 12:35:09
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.8 kb
#include<cstdio>
#include<list>
#include<algorithm>
#define pb push_back
#define nxt (*it)
#define FOR(i,a,b)\
   for(int i=a; i<=b; ++i)
#define ALL(g)\
   for(typeof(g.begin()) it=g.begin(); it!=g.end(); ++it)
#define infile "radiatie.in"
#define outfile "radiatie.out"
#define nMax 15005
#define mMax 30005
#define logMax 17
using namespace std;

struct edge{
    int cost, x, y;
    bool operator < (const edge &that)const{
        return cost < that.cost;
    }
} E[mMax];

int T[nMax], R[nMax];

int P[logMax][nMax], PC[logMax][nMax], L[nMax];

list < int > v[nMax];

int N, M, K;

inline int Find(int x){
    int r, y;
    for(r = x; T[r] != r; r = T[r]);

    while(T[x] != x){
        y = T[x];
        T[x] = r;
        x = y;
    }

    return r;
}

inline void addEdge(int x, int y, int c){
    P [0][y] = x;
    PC[0][y] = c;

    v[x].pb(y);
}

inline void Union(const edge &e){
    int x = Find(e.x), y = Find(e.y);

    if(R[x] < R[y]){
        T[x] = y;
        addEdge(e.y, e.x, e.cost);
    }
    else{
        T[y] = x;
        addEdge(e.x, e.y, e.cost);
    }

    if(R[x] == R[y])
        R[x] ++;
}

void DFS(int x, int lev){
    L[x] = lev;

    ALL(v[x])
       DFS(nxt, lev + 1);
}

void process(){
    sort(E + 1, E + M + 1);

    FOR(i,1,N)
       T[i] = i, R[i] = 1;

    for(int i = 1, dimArb = -1; i <= M && dimArb < N; ++ i){
        if( Find(E[i].x) == Find(E[i].y))
            continue;

        Union(E[i]);
        dimArb ++;
    }

    FOR(i,1,N)
       if(T[i] == i)
          DFS(i, 1);

    for(int j = 1; j <= N; ++ j)
       for(int i = 1; (1 << i) < N; ++ i){
           P[i][j] = P[i-1][P[i-1][j]];
           PC[i][j] = max(PC[i-1][j], PC[i-1][P[i-1][j]]);
       }
}

int path(int x, int y){
    if(L[x] > L[y])
      swap(x, y);

    int cmax = 0, log1, log2;
    for(log1 = 0; (1 << log1) < L[x]; ++ log1);
    for(log2 = 0; (1 << log2) < L[y]; ++ log2);

    for(; log1; -- log1)
       if(L[x] - (1 << log1) >= L[y]){
           cmax = max(cmax, PC[log1][x]);
           x = P[log1][x];
       }

    if(x == y)
       return cmax;

    for(; log2; -- log2)
       if(P[log2][x] && P[log2][x] != P[log2][y]){
           cmax = max(cmax, max(PC[log2][x], PC[log2][y]));
           x = P[log2][x];
           y = P[log2][y];
       }

    cmax = max(cmax, max(PC[0][x], PC[0][y]));

    return cmax;
}


int main(){
    freopen(infile, "r", stdin);
    freopen(outfile, "w", stdout);

    scanf("%d %d %d", &N, &M, &K);

    FOR(i,1,M)
        scanf("%d %d %d", &E[i].x, &E[i].y, &E[i].cost);

    process();

    int x, y;
    while(K--){
        scanf("%d %d", &x, &y);

        printf("%d\n", path(x,y));
    }

    fclose(stdin);
    fclose(stdout);

    return 0;
}