#include <bits/stdc++.h>
using namespace std;
int n, m, q, ans;
map<int, int> boss[100010];
map<pair<int, int>, int> mp;
vector<pair<int, int> > vt[100010];
int findf(int x, int col) {
  if (!boss[col].count(x) || x == boss[col][x]) {
    boss[col][x] = x;
    return x;
  }
  return boss[col][x] = findf(boss[col][x], col);
}
void dsu(int x, int y, int col) {
  x = findf(x, col);
  y = findf(y, col);
  if (x != y) {
    boss[col][y] = x;
  }
  return;
}
int main() {
  int i, j, a, b, c;
  cin >> n >> m;
  for (i = 0; i < m; i++) {
    cin >> a >> b >> c;
    a--, b--, c--;
    dsu(a, b, c);
  }
  for (i = 0; i < m; i++) {
    for (map<int, int>::iterator it = boss[i].begin(); it != boss[i].end();
         it++) {
      a = it->first;
      b = it->second;
      vt[a].push_back(make_pair(i, b));
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < vt[i].size(); j++) {
      vt[i][j].second = findf(i, vt[i][j].first);
    }
  }
  cin >> q;
  for (i = 0; i < q; i++) {
    cin >> a >> b;
    a--, b--;
    if (vt[a].size() >= vt[b].size()) {
      swap(a, b);
    }
    if (mp.count(make_pair(a, b))) {
      cout << mp[make_pair(a, b)] << endl;
      continue;
    }
    ans = 0;
    for (j = 0; j < vt[a].size(); j++) {
      if (binary_search(vt[b].begin(), vt[b].end(), vt[a][j])) {
        ans++;
      }
    }
    mp[make_pair(a, b)] = ans;
    cout << ans << endl;
  }
  return 0;
}
