#include<bits/stdc++.h>
using namespace std;
#define ll long long
namespace sss{
const int N = 1e4+5, M = 5e4+5;
struct Edge{
int u, v, w;
}edge[M], edges[M];
int n, m;
ll ans;
int pa[N];
int tot;
int find(int x){ return x == pa[x] ? x : find(pa[x]); }
bool cmp(Edge a, Edge b){
return a.w > b.w;
}
void kruskal(){
sort(edge + 1, edge + 1 + m, cmp);
int cnt = 0;
for (int i = 1;i <= m;i++){
if (cnt == n - 1) break;
int fu = find(edge[i].u), fv = find(edge[i].v);
if (fu == fv) continue;
pa[fu] = fv;
edges[++tot] = (Edge){edge[i].u, edge[i].v, edge[i].w};
ans += edge[i].w;
++cnt;
}
}
int main1(){
cin >> n >> m;
for (int i = 1;i <= n;i++) pa[i] = i;
cout << '\n';
for (int i = 1;i <= m;i++){
cin >> edge[i].u >> edge[i].v >> edge[i].w;
}
kruskal();
return 0;
}
}
const int N = 1e4+5, M = 5e4+5;
#define lid (id << 1)
#define rid (id << 1 | 1)
using sss::n;
using sss::m;
struct node{
int l, r, mn;
}tr[N];
int head[N], nxt[N << 1], to[N << 1], val[N << 1], cccnnnttt;
int anc[N][20], d[N], w[N][20];
bool vis[N];
int a[N];
void add(int u, int v, int w){
to[++cccnnnttt] = v;
val[cccnnnttt] = w;
nxt[cccnnnttt] = head[u];
head[u] = cccnnnttt;
}
void dfs(int u, int f){
vis[u] = 1;
for (int i = head[u];i;i = nxt[i]){
int v = to[i];
if (v == f) continue;
d[v] = d[u] + 1;
anc[v][0] = u;
w[v][0] = val[i];
dfs(v, u);
}
//cout << '#' << u << ' ' << anc[u][0] << ' ' << w[u][0] << ' ' << d[u] << '\n';
}
void init(){
for (int j = 1;j <= 18;j++){
for (int i = 1;i <= n;i++){
anc[i][j] = anc[anc[i][j - 1]][j - 1];
w[i][j] = min(w[i][j - 1], w[anc[i][j - 1]][j - 1]);
}
}
}
int LCA(int u, int v){
if (d[u] < d[v]) swap(u, v);
int res = INT_MAX;
for (int i = 18;i >= 0;i--){
if (d[anc[u][i]] >= d[v]) u = anc[u][i], res = min(res, w[u][i]);
}
if (u == v) return res;
for (int i = 18;i >= 0;i--){
if (anc[u][i] != anc[v][i]) u = anc[u][i], v = anc[v][i], res = min(res, min(w[u][i], w[v][i]));
}
res = min(res, min(w[u][0], w[v][0]));
return res;
}
int main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
sss::main1();
for (int i = 1;i <= sss::tot;i++){
add(sss::edges[i].u, sss::edges[i].v, sss::edges[i].w);
add(sss::edges[i].v, sss::edges[i].u, sss::edges[i].w);
//cout << sss::edges[i].u << ' ' << sss::edges[i].v << ' ' << sss::edges[i].w << '\n';
}
for (int i = 1;i <= n;i++){
if (!vis[i]){
d[i] = 1;
dfs(i, 0);
w[i][0] = INT_MAX;
//anc[i][0] = i;
}
}
init();
int q;
cin >> q;
while (q--){
int x, y;
cin >> x >> y;
if (sss::find(x) != sss::find(y)){
cout << "-1\n";
}
else{
cout << LCA(x, y) << '\n';
}
}
return 0;
}
/*
4 3
1 2 4
2 3 3
3 1 1
4
1 3
1 4
1 2
2 3
*/
样例输出
0
-1
0