#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=1005;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=1000000007;
const int INF=1000000010;
const ll MAX=1ll<<55;
const double pi=acos(-1.0);
typedef double db;
typedef unsigned long long ull;
struct node {
int x,y;
node(){}
node(int x,int y):x(x),y(y){}
bool operator < (const node a) const {
return x>a.x;
}
};
priority_queue<node>Q;
int n,m,q[N],f[N],d[N],dis[N];
int tot,u[N],v[2*N],w[2*N],pre[2*N];
void add(int a,int b,int c) {
v[tot]=b;w[tot]=c;pre[tot]=u[a];u[a]=tot++;
}
int find_f(int a) {
return f[a]==a ? a:f[a]=find_f(f[a]);
}
void unio(int a,int b) {
int fa=find_f(a),fb=find_f(b);
if (fa!=fb) f[fa]=fb;
}
int getmin(int a,int b) {
int i,j,k,ret=INF;
node now;
for (i=1;i<=m;i++) {
for (j=1;j<=n;j++) q[j]=0,dis[j]=INF;
dis[a]=d[i];Q.push(node(d[i],a));
while (!Q.empty()) {
now=Q.top();Q.pop();
if (q[now.y]||now.x-d[i]>ret) continue ;
q[now.y]=1;
for (k=u[now.y];k!=-1;k=pre[k])
if (!q[v[k]]&&w[k]>=d[i]&&max(now.x,w[k])<dis[v[k]]) {
dis[v[k]]=max(now.x,w[k]);Q.push(node(dis[v[k]],v[k]));
}
}
ret=min(ret,dis[b]-d[i]);
}
return ret;
}
int main()
{
int a,b,i,q,fa,fb;
while (scanf("%d%d", &n, &m)!=EOF) {
for (tot=0,i=1;i<=n;i++) f[i]=i,u[i]=-1;
for (i=1;i<=m;i++) {
scanf("%d%d%d", &a, &b, &d[i]);
add(a,b,d[i]);add(b,a,d[i]);unio(a,b);
}
scanf("%d", &q);
while (q--) {
scanf("%d%d", &a, &b);
fa=find_f(a);fb=find_f(b);
if (fa!=fb) printf("-1\n");
else printf("%d\n", getmin(a,b));
}
}
return 0;
}