#include <bits/stdc++.h>
int parent[105][105];
int query[105];
int getAncestor(int v, int c) {
  if (parent[v][c] == v)
    return v;
  else if (parent[parent[v][c]][c] == parent[v][c])
    return parent[v][c];
  else
    parent[v][c] = getAncestor(parent[v][c], c);
  return parent[v][c];
}
int main(void) {
  int n, m;
  int a, b, c;
  int q;
  int count;
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) parent[i][j] = i;
  }
  for (int j = 1; j <= m; j++) {
    scanf("%d %d %d", &a, &b, &c);
    if (getAncestor(a, c) != getAncestor(b, c))
      parent[getAncestor(b, c)][c] = a;
  }
  scanf("%d", &q);
  for (int k = 1; k <= q; k++) {
    scanf("%d %d", &a, &b);
    count = 0;
    for (int j = 1; j <= m; j++) {
      if (getAncestor(a, j) == getAncestor(b, j)) count++;
    }
    query[k] = count;
  }
  for (int k = 1; k <= q; k++) printf("%d\n", query[k]);
  return 0;
}
