http://codevs.cn/problem/1519/
题面在这↑;
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL maxx=500000;
LL n,m;
struct ha
{
LL f,t,d;
}es[maxx];
ha cc[maxx];
LL tot=0,first[maxx],next[maxx];
void build(LL f,LL t,LL d)
{
es[++tot]=(ha){f,t,d};
next[tot]=first[f];
first[f]=tot;
}
LL cp(ha x,ha y)
{return x.d<y.d;}
int fax[maxx];
LL find(LL x)
{
if(fax[x]==x)
return x;
else
return fax[x]=find(fax[x]);
}
void Krus()
{
for(int i=1;i<=n;i++)
fax[i]=i;
sort(cc+1,cc+1+m,cp);
for(int i=1;i<=m;i++)
{
LL x=cc[i].f,y=cc[i].t;
if(find(x)!=find(y))
{
fax[find(x)]=find(y);
build(cc[i].f,cc[i].t,cc[i].d);
build(cc[i].t,cc[i].f,cc[i].d);
}
}
}
LL fa[maxx][30],sd[maxx],dis[maxx][30];
void dfs(LL x)
{
for(int i=first[x];i!=0;i=next[i])
{
LL v=es[i].t;
if(sd[v]==0)
{
sd[v]=sd[x]+1;
fa[v][0]=x;
dis[v][0]=es[i].d;
for(int i=1;i<=25;i++)
{
fa[v][i]=fa[fa[v][i-1]][i-1];
dis[v][i]=max(dis[v][i-1],dis[fa[v][i-1]][i-1]);
}
dfs(v);
}
}
}
LL lca(LL u,LL v)
{
LL Max=0;
if(sd[u]>sd[v])
swap(u,v);
LL tt=sd[v]-sd[u];
for(int i=0;i<=25;i++)
{
if((tt>>i)&1==1)
{
Max=max(Max,dis[v][i]);
v=fa[v][i];
}
}
for(int i=25;i>=0;i--)
{
if(fa[u][i]!=fa[v][i])
{
Max=max(Max,dis[v][i]);
Max=max(Max,dis[u][i]);
u=fa[u][i];
v=fa[v][i];
}
}
if(u!=v)
{
Max=max(Max,dis[u][0]);
Max=max(Max,dis[v][0]);
}
return Max;
}
int main()
{
scanf("%lld%lld",&n,&m);
for(int i=1;i<=m;i++)
scanf("%lld%lld%lld",&cc[i].f,&cc[i].t,&cc[i].d);
Krus();
LL q,xx,yy;
for(int i=1;i<=n;i++)
{
if(sd[i]==0)
{
sd[i]=1;
dfs(i);
}
}
scanf("%lld",&q);
for(int i=1;i<=q;i++)
{
scanf("%lld%lld",&xx,&yy);
printf("%lld\n",lca(xx,yy));
}
return 0;
}