#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> P[100100];
set<int> C[100100];
vector<int> L[100100];
map<pair<int, int>, int> ans;
int find(int c, int x) {
  if (P[c].find(x) == P[c].end()) {
    P[c][x] = x;
    return x;
  }
  if (P[c][x] == x) return x;
  P[c][x] = find(c, P[c][x]);
  return P[c][x];
}
int main() {
  ios::sync_with_stdio(false);
  int N, M, Q, i, j, k, n1, n2, n3, x, y, z;
  cin >> N >> M;
  for (i = 0; i < M; i++) {
    cin >> n1 >> n2 >> n3;
    n1--;
    n2--;
    n3--;
    if (n1 > n2) swap(n1, n2);
    P[n3][find(n3, n1)] = find(n3, n2);
    C[n1].insert(n3);
    C[n2].insert(n3);
  }
  cin >> Q;
  set<int>::iterator it;
  for (i = 0; i < N; i++) {
    for (it = C[i].begin(); it != C[i].end(); ++it) {
      L[i].push_back((*it));
    }
  }
  for (i = 0; i < Q; i++) {
    cin >> n1 >> n2;
    n1--;
    n2--;
    if (L[n1].size() > L[n2].size()) swap(n1, n2);
    if (ans.find(pair<int, int>(n1, n2)) != ans.end()) {
      cout << ans[pair<int, int>(n1, n2)] << endl;
    } else {
      int res = 0;
      for (j = 0; j < L[n1].size(); j++) {
        k = L[n1][j];
        if (P[k].find(n2) == P[k].end()) continue;
        if (find(k, n1) == find(k, n2)) res++;
      }
      ans[pair<int, int>(n1, n2)] = res;
      cout << res << endl;
    }
  }
  return 0;
}
