1 #include<cstdio>
2 #include<iostream>
3 #include<algorithm>
4 #define maxn_m 100000
5 #define maxn 50000
6 using namespace std;
7
8 struct edge1{
9 int u,v,len;
10 }e1[maxn_m];
11
12 struct edge{
13 int from,v,len;
14 }e[maxn_m];
15
16 int tot,first[maxn],n,m,q,a,b;
17 void insert(int u,int v,int len){
18 tot++;
19 e[tot].from = first[u];
20 e[tot].v = v;
21 e[tot].len = len;
22 first[u] = tot;
23 }
24
25 bool cmp(const edge1 &a,const edge1 &b){return a.len>b.len;}
26 int pre[maxn];
27 int find(int x){if(!pre[x]){return x;}else{pre[x] = find(pre[x]);return pre[x];}}
28 void unite(int x,int y){if(find(x)!=find(y))pre[find(x)]=y;}
29 void kru(){
30 sort(e1,e1+m,cmp);
31
32 for(int i = 0;i < m;i++){
33 if(find(e1[i].u) != find(e1[i].v)){
34 insert(e1[i].u,e1[i].v,e1[i].len);
35 insert(e1[i].v,e1[i].u,e1[i].len);
36 unite(e1[i].u,e1[i].v);
37 }
38 }
39 }
40
41 int depth[maxn],fa[maxn][20],mincost[maxn][20];
42 bool book[maxn];
43 void dfs(int root){
44 for(int i = first[root];i;i = e[i].from){
45 int v = e[i].v;
46 if(!book[v]){
47 book[v] = true;
48 depth[v] = depth[root]+1;
49 fa[v][0] = root;
50 mincost[v][0] = e[i].len;
51 for(int i = 1;i <= 18;i++){
52 fa[v][i] = fa[fa[v][i-1]][i-1];
53 mincost[v][i] = min(mincost[fa[v][i-1]][i-1],mincost[v][i-1]);
54 }
55 dfs(v);
56 }
57 }
58 }
59
60 int lca(int u,int v){
61 if(depth[u] < depth[v]) swap(u,v);
62
63 int maxx = 999999999;
64 for(int i = 18;i >= 0;i--){
65 if(depth[fa[u][i]] >= depth[v]){
66 if(mincost[u][i]) maxx = min(maxx,mincost[u][i]);
67 u = fa[u][i];
68 }
69 }
70
71 if(u == v) return maxx;
72
73 for(int i = 18;i >= 0;i--){
74 if(fa[u][i] != fa[v][i]){
75 if(mincost[u][i]) maxx = min(maxx,mincost[u][i]);
76 if(mincost[v][i]) maxx = min(maxx,mincost[v][i]);
77 u = fa[u][i];
78 v = fa[v][i];
79 }
80 }
81
82 if(mincost[u][0]) maxx = min(mincost[u][0],maxx);
83 if(mincost[v][0]) maxx = min(mincost[v][0],maxx);
84
85 return maxx;
86 }
87
88 int main(){
89
90 scanf("%d%d",&n,&m);
91
92 for(int i = 0;i < m;i++){
93 scanf("%d%d%d",&e1[i].u,&e1[i].v,&e1[i].len);
94 }
95
96 kru();
97
98 book[1] = true;
99 depth[1] = 1;
100 dfs(1);
101
102 scanf("%d",&q);
103
104 for(int i = 0;i < q;i++){
105 scanf("%d%d",&a,&b);
106 if(find(a) != find(b)) printf("-1\n");
107 else printf("%d\n",lca(a,b));
108 }
109
110 return 0;
111 }