package Day_62;
import java.util.Arrays;
import java.util.Scanner;
public class K97_xiaomingguanggongyuan {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] graph = new int[n+1][n+1];
for(int i=0;i<n+1;i++) {
Arrays.fill(graph[i], Integer.MAX_VALUE);
}
for(int i=0;i<m;i++) {
int x = scan.nextInt();
int y = scan.nextInt();
int val = scan.nextInt();
graph[x][y]=val;
graph[y][x]=val;
}
for(int q=1;q<=n;q++) {
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
graph[i][j]=Math.min(graph[i][j], graph[i][q]+graph[q][j]);
}
}
}
int k = scan.nextInt();
for(int i=0;i<k;i++) {
int x = scan.nextInt();
int y = scan.nextInt();
if(graph[x][y]==Integer.MAX_VALUE) {
System.out.println(-1);
}else {
System.out.println(graph[x][y]);
}
}
}
}