Cod sursa(job #1496584)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 5 octombrie 2015 11:13:53
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.62 kb
#include <cstdio>
#include <algorithm>
#define MAXN 15000
#define MAXK 15000
#define MAXM 30000
typedef struct{
    int a, b, c;
}mycreation;
mycreation v[MAXM];
int q, n, val[2*MAXN-1], cost[2*MAXN-1], next[2*MAXN-1], lista[MAXN+1], viz[MAXN+1], t[MAXN+1], h[MAXN+1], s[14][MAXN+1], d[14][MAXN+1];
inline int max2(int x, int y){
    if(x>y){
        return x;
    }
    return y;
}
bool cmp(const mycreation x, const mycreation y){
    return (x.c<y.c);
}
int find(int x){
    if(t[x]==x){
        return x;
    }
    t[x]=find(t[x]);
    return t[x];
}
inline void adauga(int x, int y, int z){
    q++;
    val[q]=y;
    cost[q]=z;
    next[q]=lista[x];
    lista[x]=q;
}
void dfs(int x){
    int p=lista[x];
    viz[x]=1;
    while(p){
        if(viz[val[p]]==0){
            s[0][val[p]]=x;
            d[0][val[p]]=cost[p];
            h[val[p]]=h[x]+1;
            dfs(val[p]);
        }
        p=next[p];
    }
}
inline void stramosi(){
    int i, j;
    for(i=1; (1<<i)<=n; i++){
        for(j=1; j<=n; j++){
            s[i][j]=s[i-1][s[i-1][j]];
            d[i][j]=max2(d[i-1][j], d[i-1][s[i-1][j]]);
        }
    }
}
inline int raspuns(int x, int y){
    int sol=0, aux, pas;
    if(h[x]<h[y]){
        aux=x;
        x=y;
        y=aux;
    }
    for(pas=13; pas>=0; pas--){
        if(h[x]-h[y]>=(1<<pas)){
            sol=max2(sol, d[pas][x]);
            x=s[pas][x];
        }
    }
    if(x==y){
        return sol;
    }
    for(pas=13; pas>=0; pas--){
        if(s[pas][x]!=s[pas][y]){
            sol=max2(sol, max2(d[pas][x], d[pas][y]));
            x=s[pas][x];
            y=s[pas][y];
        }
    }
    sol=max2(sol, max2(d[0][x], d[0][y]));
    return sol;
}
int main(){
    int m, k, i, x, y;
    FILE *fin, *fout;
    fin=fopen("radiatie.in", "r");
    fout=fopen("radiatie.out", "w");
    fscanf(fin, "%d%d%d", &n, &m, &k);
    for(i=0; i<m; i++){
        fscanf(fin, "%d%d%d", &v[i].a, &v[i].b, &v[i].c);
    }
    std::sort(v, v+m, cmp);
    for(i=1; i<=n; i++){
        t[i]=i;
    }
    for(i=0; i<m; i++){
        if(find(v[i].a)!=find(v[i].b)){
            t[find(v[i].a)]=find(v[i].b);
            adauga(v[i].a, v[i].b, v[i].c);
            adauga(v[i].b, v[i].a, v[i].c);
        }
    }
    for(i=1; i<=n; i++){
        if(viz[i]==0){
            s[0][i]=0;
            d[0][i]=0;
            h[i]=1;
            dfs(i);
        }
    }
    stramosi();
    for(i=0; i<k; i++){
        fscanf(fin, "%d%d", &x, &y);
        fprintf(fout, "%d\n", raspuns(x, y));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}