#include <bits/stdc++.h>
using namespace std;
int p[100005 * 2];
int a[100005], b[100005], c[100005];
int n, m, q;
vector<int> color[100005];
int start[100005];
map<pair<int, int>, int> dp;
int find(int a) {
  if (p[a] != a) p[a] = find(p[a]);
  return p[a];
}
void u(int a, int b) { p[a] = b; }
int getidx(int node, int cc) {
  return start[node] +
         (lower_bound(color[node].begin(), color[node].end(), cc) -
          color[node].begin());
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < m; ++i) {
    cin >> a[i] >> b[i] >> c[i];
    color[a[i]].push_back(c[i]);
    color[b[i]].push_back(c[i]);
  }
  start[0] = 0;
  for (int i = 1; i <= n; ++i) {
    start[i] = start[i - 1] + color[i - 1].size();
    sort(color[i].begin(), color[i].end());
    color[i].erase(unique(color[i].begin(), color[i].end()), color[i].end());
  }
  for (int i = 0; i < 100005 * 2; ++i) p[i] = i;
  for (int i = 0; i < m; ++i) {
    int aidx = getidx(a[i], c[i]);
    int bidx = getidx(b[i], c[i]);
    int pa = find(aidx);
    int pb = find(bidx);
    u(pa, pb);
  }
  cin >> q;
  for (int i = 0; i < q; ++i) {
    int x, y;
    cin >> x >> y;
    if (x > y) swap(x, y);
    if (color[x].size() > color[y].size()) swap(x, y);
    map<pair<int, int>, int>::iterator iter = dp.find(make_pair(x, y));
    if (iter != dp.end()) {
      cout << iter->second << endl;
    } else {
      int ans = 0;
      for (int j = 0; j < color[x].size(); ++j) {
        if (binary_search(color[y].begin(), color[y].end(), color[x][j])) {
          int xidx = getidx(x, color[x][j]);
          int yidx = getidx(y, color[x][j]);
          int px = find(xidx);
          int py = find(yidx);
          if (px == py) ans++;
        }
      }
      dp[make_pair(x, y)] = ans;
      cout << ans << endl;
    }
  }
  return 0;
}
