n,m = map(int,input().split()) edge = [{} for i in range(n)] Edge = [] for _ in range(m): u,v,c = map(int,input().split()) edge[u-1][v-1] = 1 Edge.append((u-1,v-1,c)) cost = [[10**18 for j in range(n)] for i in range(n)] for i in range(n): cost[i][i] = 0 for u,v,c in Edge: cost[u][v] = 1 for k in range(n): for i in range(n): for j in range(n): if cost[i][j] > cost[i][k] + cost[k][j]: cost[i][j] = cost[i][k] + cost[k][j] Edge.sort(key=lambda x:x[2]) ans = [[-1 for j in range(n)] for i in range(n)] def dfs(i,v,cu,cv,w): for nv in edge[v]: if (v,nv) == (cu,cv): edge[v][nv] = -1 if cost[i][v]!=-10**18: if cost[i][nv] > cost[i][v] + edge[v][nv]: cost[i][nv] = cost[i][v] + edge[v][nv] if cost[i][nv] < -n: cost[i][nv] = -10**18 if cost[i][nv]<=0 and ans[i][nv]==-1: ans[i][nv] = w dfs(i,nv,cu,cv,w) else: if cost[i][nv]!=-10**18: cost[i][nv] = -10**18 if cost[i][nv]<=0 and ans[i][nv]==-1: ans[i][nv] = w dfs(i,nv,cu,cv,w) for u,v,c in Edge: for i in range(n): if cost[i][u] != 10**18: dfs(i,u,u,v,c) Q = int(input()) res = [-1]*Q for i in range(Q): s,t = map(int,input().split()) res[i] = ans[s-1][t-1] print(*res,sep="\n")