#include <bits/stdc++.h>
using namespace std;
const int INF = 100009;
unordered_map<int, int> f[INF], old[INF];
int n, m, q;
inline int find(int x, int c) {
  if (f[x][c] < 0) return x;
  return f[x][c] = find(f[x][c], c);
}
inline void merge(int x, int y, int c) {
  if (f[x].find(c) == f[x].end()) f[x][c] = -1;
  if (f[y].find(c) == f[y].end()) f[y][c] = -1;
  x = find(x, c), y = find(y, c);
  if (x == y) return;
  f[y][c] += f[x][c];
  f[x][c] = y;
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1, x, y, c; i <= m; i++) {
    scanf("%d %d %d", &x, &y, &c);
    merge(x, y, c);
  }
  scanf("%d", &q);
  int a, b;
  while (q--) {
    scanf("%d %d", &a, &b);
    if (f[a].size() > f[b].size()) swap(a, b);
    if (old[a].find(b) == old[a].end()) {
      int ans = 0;
      for (auto &c : f[a])
        if (f[b].find(c.first) != f[b].end() &&
            find(a, c.first) == find(b, c.first))
          ans++;
      old[a][b] = ans;
    }
    printf("%d\n", old[a][b]);
  }
}
