Cod sursa(job #1712310)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 2 iunie 2016 17:26:07
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.23 kb
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 15005;

int Log[N], lvl[N], d[N][15], t[N][15], boss[N], X,Y, i, n,m,q;
vector< pair<int,int> > v[N];
vector< pair<int,int> > :: iterator it;

struct fun {int x,y,c;};
fun a[N<<1];

bool cmp(fun a, fun b) {return a.c<b.c;}

int sef(int x)
{
    if(x==boss[x]) return x;
    return boss[x]=sef(boss[x]);
}

void dfs(int node)
{
     int i;
     for(i=1; (1<<i)<=lvl[node]; ++i)
     {
         t[node][i] = t[ t[node][i-1] ][i-1];
         d[node][i] = max(d[ t[node][i-1] ][i-1], d[node][i-1]);
     }

     for(auto &it:v[node])
        if( !lvl[ it.first ] && it.first!=1 )
        {
            t[it.first][0] = node;
            d[it.first][0] = it.second;
            lvl[it.first] = lvl[node]+1;
            dfs( it.first);
        }
}

int kth(int node, int k, int &ans)
{
     int bt;ans=0;
     while(k)
     {
         bt = Log[k&(-k)];
         ans = max(ans, d[node][bt]);
         node = t[node][bt];
         k-=(1<<bt);
     }
     return node;
}

int path(int x, int y)
{
    if(lvl[x]<lvl[y]) swap(x,y);

    int i, X,Y, ans1, ans2, ans;

    x = kth(x, lvl[x]-lvl[y], ans);

    for(i=1; (1<<i)<=lvl[x]; i<<=1);
    for(i>>=1; i; i>>=1)
    {
         X = kth(x, i, ans1);
         Y = kth(y, i, ans2);

         if(X!=Y)
         {
             ans = max(ans, ans1);
             ans = max(ans, ans2);
             x=X;
             y=Y;
         }
    }
    return ans;
}

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

    scanf("%d%d%d", &n, &m, &q);

    for(i=1; i<=m; ++i)
        scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].c);

    sort(a+1, a+m+1, cmp);

    for(i=0; i<=13; ++i) Log[1<<i]=i;
    for(i=1; i<=n; ++i) boss[i]=i;

    for(i=1; i<=m; ++i)
    {
        X=sef(a[i].x);
        Y=sef(a[i].y);
        if(X!=Y)
        {
            boss[X]=Y;
            v[a[i].x].push_back({a[i].y, a[i].c});
            v[a[i].y].push_back({a[i].x, a[i].c});
        }
    }

    dfs(1);

    while(q--)
    {
        scanf("%d%d", &X, &Y);
        printf("%d\n", path(X,Y));
    }

    return 0;
}