import sys sys.setrecursionlimit(2*10**5) 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,w): for nv in edge[v]: 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,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,w) for u,v,c in Edge: edge[u][v] = -1 for i in range(n): if cost[i][u] != 10**18: if cost[i][v] > cost[i][u] + edge[u][v]: cost[i][v] = cost[i][u] + edge[u][v] if cost[i][v] < -n: cost[i][v] = -10**18 if ans[i][v] == -1: ans[i][v] = c dfs(i,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")