def solve():
    while True:
        N, B = map(int, input().split())
        if N == 0 and B == 0:
            break
        adj = [[0 for _ in range(N+1)] for _ in range(N+1)]
        for _ in range(B):
            I, J, P = map(int, input().split())
            adj[I][J] = P
            adj[J][I] = P
        C = int(input())
        for _ in range(C):
            X, Y = map(int, input().split())
            dist = [0 for _ in range(N+1)]
            visited = [False for _ in range(N+1)]
            dist[X] = float('inf')
            for _ in range(N):
                max_i = -1
                for i in range(1, N+1):
                    if not visited[i] and (max_i == -1 or dist[i] > dist[max_i]):
                        max_i = i
                if dist[max_i] == 0:
                    break
                visited[max_i] = True
                for i in range(1, N+1):
                    if min(dist[max_i], adj[max_i][i]) > dist[i]:
                        dist[i] = min(dist[max_i], adj[max_i][i])
            print(dist[Y])

solve()
