#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
#define For(i,x,y) for(int i=x;i<=y;i++)
const int MAX = 1e6+10;
const int INF = 0x3f3f3f3f;
struct Node{
int x,y,dis;
void input(int _x,int _y,int _z)
{
x=_x,y=_y,dis=_z;
}
}node[MAX];
struct Edge{int to,nxt,w;}edge[MAX];
int head[MAX],tot=1,father[MAX];
int n,q,m,fa[MAX][21],w[MAX][21],h[MAX];
bool vis[MAX];
void addedge(int u,int v,int w)
{
edge[tot].to=v;
edge[tot].nxt=head[u];
edge[tot].w=w;
head[u]=tot++;
}
int find(int x)
{
if(father[x]!=x) father[x]=find(father[x]);
return father[x];
}
bool cmp(Node a,Node b)
{
return a.dis>b.dis;
}
void krusle()
{
sort(node+1,node+1+n,cmp);
For(i,1,m)
{
int p=find(node[i].x),q=find(node[i].y);
if(p!=q)
{
father[p]=q;
addedge(node[i].x,node[i].y,node[i].dis);
addedge(node[i].y,node[i].x,node[i].dis);
}
}
}
void dfs(int s)
{
vis[s]=true;
for(int i=head[s];i!=-1;i=edge[i].nxt)
{
int v=edge[i].to;
if(vis[v]) continue;
h[v]=h[s]+1;
fa[v][0]=s;w[v][0]=edge[i].w;
dfs(v);
}
}
int lca(int x,int y)
{ if(find(x)!=find(y)) return -1;
int ans=INF;
if(h[x]>h[y]) swap(x,y);
for(int i=20;i>=0;i--)
{
if(h[fa[y][i]]>=h[x])
{
ans=min(ans,w[y][i]);
y=fa[y][i];
}
}
if(x==y) return ans;
for(int i=20;i>=0;i--)
{
if(fa[x][i]!=fa[y][i])
{
ans=min(ans,min(fa[x][i],fa[y][i]));
x=fa[x][i],y=fa[y][i];
}
}
ans=min(ans,min(w[x][0],w[y][0]));
return ans;
}
int main()
{
memset(head,-1,sizeof(head));
cin>>n>>m;
For(i,1,m)
{
int x,y,z;cin>>x>>y>>z;
node[i].input(x,y,z);
}
For(i,1,n) father[i]=i;
krusle();
for(int i=20;i>=0;i--)
{
if(!vis[i])
{
h[i]=1;
dfs(i);
fa[i][0]=i;
w[i][0]=INF;
}
}
for(int i=1;i<=20;i++)
{
for(int j=1;j<=n;j++)
{
fa[j][i]=fa[fa[j][i-1]][i-1];
w[j][i]=min(w[j][i-1],w[fa[j][i-1]][i-1]);
}
}
cin>>q;
while(q--)
{
int x,y;cin>>x>>y;
printf("%d\n",lca(x,y));
}
return 0;
}
不知道为什么样例过了,但sub #0全WA