#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void solve() {
    while (1) {
        int N, B;
        scanf("%d %d", &N, &B);

        if (N == 0 && B == 0) {
            break;
        }

        int adj[N + 1][N + 1];

        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= N; j++) {
                adj[i][j] = 0;
            }
        }

        for (int i = 0; i < B; i++) {
            int I, J, P;
            scanf("%d %d %d", &I, &J, &P);
            adj[I][J] = P;
            adj[J][I] = P;
        }

        int C;
        scanf("%d", &C);

        for (int i = 0; i < C; i++) {
            int X, Y;
            scanf("%d %d", &X, &Y);

            int dist[N + 1];
            bool visited[N + 1];

            for (int j = 1; j <= N; j++) {
                dist[j] = 0;
                visited[j] = false;
            }

            dist[X] = 2147483647; // INT_MAX

            for (int j = 0; j < N; j++) {
                int max_i = -1;
                for (int k = 1; k <= N; k++) {
                    if (!visited[k] && (max_i == -1 || dist[k] > dist[max_i])) {
                        max_i = k;
                    }
                }
                if (dist[max_i] == 0) {
                    break;
                }
                visited[max_i] = true;
                for (int k = 1; k <= N; k++) {
                    if (dist[max_i] < adj[max_i][k] && dist[k] < dist[max_i]) {
                        dist[k] = dist[max_i];
                    } else if (dist[max_i] > adj[max_i][k] && dist[k] < adj[max_i][k]) {
                        dist[k] = adj[max_i][k];
                    }
                }
            }

            printf("%d\n", dist[Y]);
        }
    }
}

int main() {
    solve();
    return 0;
}