wa 3 4 5 6 11 12
#include<bits/stdc++.h>
using namespace std;
int n,m,mi=0;
int pv[100010];
int parent[100010];
int find(int x){
if(parent[x]!=x)
parent[x]=find(parent[x]);
return parent[x];
}
struct edgee{
int from,to,w;
}edge[300010];
struct node{
int v,to,next;
}e[300010];
int head[100010],cnt=0;
void add(int a,int b,int v){
e[cnt].to=b;
e[cnt].v=v;
e[cnt].next=head[a];
head[a]=cnt++;
}
int deep[100010],ancestor[100010][25],pathv[100010][25];
void dfs(int x,int fa){
deep[x]=deep[fa]+1;
ancestor[x][0]=fa;
for(int i=1;(1<<i)<=deep[x];i++){
ancestor[x][i]=ancestor[ancestor[x][i-1]][i-1];
pathv[x][i]=max(pathv[x][i-1],pathv[ancestor[x][i-1]][i-1]);
}
for(int i=head[x];i!=-1;i=e[i].next)
if(e[i].to!=fa)
pathv[e[i].to][0]=e[i].v,dfs(e[i].to,x);
}
int lca(int a,int b){
int maxp=0;
if(deep[a]<deep[b]){
int t=a; a=b; b=t;
}
for(int i=24;i>=0;i--)
if(deep[a]-(1<<i)>=deep[b])
maxp=max(maxp,pathv[a][i]),a=ancestor[a][i];
if(a==b)
return maxp;
for(int i=24;i>=0;i--){
if(ancestor[a][i]!=ancestor[b][i]){
maxp=max(maxp,pathv[a][i]); maxp=max(maxp,pathv[b][i]);
a=ancestor[a][i]; b=ancestor[b][i];
}
}
maxp=max(maxp,pathv[a][0]); maxp=max(maxp,pathv[b][0]);
return maxp;
}
bool cmp(edgee a,edgee b){
return a.w<b.w;
}
signed main(){
cin>>n>>m;
for(int i=0;i<=(1<<n);i++)
parent[i]=i,head[i]=-1;
for(int i=1;i<=m;i++){
int a,b,v; cin>>a>>b>>v;
if(a==b)
continue;
mi++;
edge[mi].from=a, edge[mi].to=b, edge[mi].w=v;
}
sort(edge+1,edge+1+mi,cmp);
int cnt2=0;
for(int i=1;i<=mi;i++){
int a=find(edge[i].from),b=find(edge[i].to),v=edge[i].w;
if(a==b)
continue;
parent[a]=b;
add(a,b,v); add(b,a,v);
cnt2++;
if(cnt2==n-1)
break;
}
for(int i=1;i<=n;i++){
if(deep[i]==0)
deep[i]=1,dfs(i,0);
}
int q; cin>>q;
while(q--){
int a,b; cin>>a>>b;
if(find(a)!=find(b))
cout<<"impossible"<<endl;
else
cout<<lca(a,b)<<endl;
}
return 0;
}