#include <bits/stdc++.h>
using namespace std;
int n, m;
struct SUS {
  vector<int> up;
  SUS() {}
  SUS(int n) {
    up.resize(n);
    iota(up.begin(), up.end(), 0);
  }
  int get_root(int v) {
    if (up[v] == v) return v;
    return up[v] = get_root(up[v]);
  }
  void merge(int a, int b) { up[get_root(a)] = get_root(b); }
};
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  vector<vector<pair<int, int>>> edg(m + 100);
  for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    edg[c].emplace_back(a, b);
  }
  map<pair<int, int>, int> cnt;
  vector<SUS> isuses;
  for (int i = 0; i < ((int)edg.size()); i++) {
    if (((int)edg[i].size()) < 350) {
      vector<int> all;
      for (pair<int, int> e : edg[i]) {
        all.push_back(e.first);
        all.push_back(e.second);
      }
      sort(all.begin(), all.end());
      all.resize(unique(all.begin(), all.end()) - all.begin());
      SUS sus(((int)all.size()));
      for (pair<int, int> e : edg[i]) {
        sus.merge(lower_bound(all.begin(), all.end(), e.first) - all.begin(),
                  lower_bound(all.begin(), all.end(), e.second) - all.begin());
      }
      for (int i = 0; i < ((int)all.size()); i++) {
        for (int j = 0; j < ((int)all.size()); j++) {
          if (sus.get_root(i) == sus.get_root(j)) {
            cnt[make_pair(all[i], all[j])]++;
          }
        }
      }
    } else {
      isuses.push_back(SUS(n));
      for (pair<int, int> e : edg[i]) {
        isuses.back().merge(e.first, e.second);
      }
    }
  }
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    int rez = cnt[make_pair(a, b)];
    for (int j = 0; j < ((int)isuses.size()); j++) {
      rez += (isuses[j].get_root(a) == isuses[j].get_root(b));
    }
    cout << rez << "\n";
  }
}
