#include <bits/stdc++.h>
using namespace std;
int w[105][105][105];
int main() {
  int n, m, i, j, k, l, a, b, c;
  scanf("%d%d", &n, &m);
  memset(w, 0, sizeof(w));
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++) w[i][i][j] = 1;
  for (i = 1; i <= m; i++) {
    scanf("%d%d%d", &a, &b, &c);
    w[a][b][c] = 1;
    w[b][a][c] = 1;
  }
  for (l = 1; l <= m; l++)
    for (k = 1; k <= n; k++)
      for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++) {
          if (w[i][k][l] == 1 && w[k][j][l] == 1) {
            w[i][j][l] = 1;
            w[j][i][l] = 1;
          }
        }
  int q, x, y;
  scanf("%d", &q);
  while (q--) {
    int ans = 0;
    scanf("%d%d", &x, &y);
    for (l = 1; l <= m; l++)
      if (w[x][y][l] == 1) ans++;
    printf("%d\n", ans);
  }
  return 0;
}
