# 【bzoj3732】Network 最小生成树+倍增LCA

6 6 8
1 2 5
2 3 4
3 4 3
1 4 8
2 5 7
4 6 2
1 2
1 3
1 4
2 3
2 4
5 1
6 2
6 1

5
5
5
4
4
7
4
5

#include <cstdio>
#include <algorithm>
using namespace std;
struct data
{
int x , y , z;
}a[30010];
int f[15010] , head[15010] , to[30010] , len[30010] , next[30010] , cnt , log[15010] , deep[15010] , fa[15010][20] , maxn[15010][20];
bool cmp(data a , data b)
{
return a.z < b.z;
}
int find(int x)
{
return x == f[x] ? x : f[x] = find(f[x]);
}
void add(int x , int y , int z)
{
to[++cnt] = y;
len[cnt] = z;
}
void dfs(int x)
{
int i;
for(i = 1 ; i <= log[deep[x]] ; i ++ )
fa[x][i] = fa[fa[x][i - 1]][i - 1] , maxn[x][i] = max(maxn[x][i - 1] , maxn[fa[x][i - 1]][i - 1]);
for(i = head[x] ; i ; i = next[i])
{
if(to[i] != fa[x][0])
{
fa[to[i]][0] = x;
maxn[to[i]][0] = len[i];
deep[to[i]] = deep[x] + 1;
dfs(to[i]);
}
}
}
int query(int x , int y)
{
int i , ans = 0;
if(deep[x] < deep[y])
swap(x , y);
for(i = log[deep[x] - deep[y]] ; i >= 0 ; i -- )
if(deep[x] - (1 << i) >= deep[y])
ans = max(ans , maxn[x][i]) , x = fa[x][i];
for(i = log[deep[x]] ; i >= 0 ; i -- )
if(fa[x][i] != fa[y][i])
ans = max(ans , max(maxn[x][i] , maxn[y][i])) , x = fa[x][i] , y = fa[y][i];
if(x != y)
ans = max(ans , max(maxn[x][0] , maxn[y][0]));
return ans;
}
int main()
{
int n , m , k , i , num = 0 , tx , ty;
scanf("%d%d%d" , &n , &m , &k);
for(i = 1 ; i <= m ; i ++ )
scanf("%d%d%d" , &a[i].x , &a[i].y , &a[i].z);
sort(a + 1 , a + m + 1 , cmp);
for(i = 1 ; i <= n ; i ++ )
f[i] = i;
for(i = 1 ; i <= m ; i ++ )
{
tx = find(a[i].x) , ty = find(a[i].y);
if(tx != ty)
{
f[tx] = ty;
num ++ ;
if(num == n - 1)
break;
}
}
for(i = 2 ; i <= n ; i ++ )
log[i] = log[i >> 1] + 1;
dfs(1);
while(k -- )
{
scanf("%d%d" , &tx , &ty);
printf("%d\n" , query(tx , ty));
}
return 0;
}

|转载请注明 [原文链接][作者] ，谢谢！

posted @ 2017-02-17 09:53  GXZlegend  阅读(269)  评论(0编辑  收藏  举报