import java.util.Scanner;

public class Barcos {
    public static void solve() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            int N = scanner.nextInt();
            int B = scanner.nextInt();

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

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

            for (int i = 0; i < B; i++) {
                int I = scanner.nextInt();
                int J = scanner.nextInt();
                int P = scanner.nextInt();
                adj[I][J] = P;
                adj[J][I] = P;
            }

            int C = scanner.nextInt();

            for (int i = 0; i < C; i++) {
                int X = scanner.nextInt();
                int Y = scanner.nextInt();

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

                dist[X] = Integer.MAX_VALUE;

                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 (Math.min(dist[max_i], adj[max_i][k]) > dist[k]) {
                            dist[k] = Math.min(dist[max_i], adj[max_i][k]);
                        }
                    }
                }

                System.out.println(dist[Y]);
            }
        }

        scanner.close();
    }

    public static void main(String[] args) {
        solve();
    }
}