#include <bits/stdc++.h>
using namespace std;
const int maxn = 100 * 1000 + 10;
vector<pair<int, int> > v[maxn];
int par[maxn], ans[maxn], aray[maxn * 2];
vector<int> w[maxn];
pair<int, int> Q[maxn];
map<int, int> mp[maxn];
inline int find_par(int id) {
  if (par[id] < 0) return id;
  return par[id] = find_par(par[id]);
}
inline void add_edge(int fi, int se) {
  int u = find_par(fi), v = find_par(se);
  if (u == v) return;
  if (par[u] < par[v]) swap(u, v);
  par[v] += par[u];
  par[u] = v;
}
int main() {
  ios_base::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  memset(par, -1, sizeof par);
  for (int i = 1; i <= m; ++i) {
    int fi, se, col;
    cin >> fi >> se >> col;
    v[col].push_back({fi, se});
  }
  int q;
  cin >> q;
  for (int i = 1; i <= q; ++i) cin >> Q[i].first >> Q[i].second;
  for (int i = 1; i <= m; ++i) {
    if (v[i].size()) {
      for (int j = 0; j < v[i].size(); ++j)
        add_edge(v[i][j].first, v[i][j].second);
      if (v[i].size() >= 500) {
        for (int j = 1; j <= q; ++j)
          if (find_par(Q[j].first) == find_par(Q[j].second)) ans[j]++;
      } else {
        int cur = 0;
        for (int j = 0; j < v[i].size(); ++j) {
          aray[cur++] = v[i][j].first;
          aray[cur++] = v[i][j].second;
        }
        sort(aray, aray + cur);
        cur = unique(aray, aray + cur) - aray;
        for (int k = 0; k < cur; ++k)
          for (int l = k + 1; l < cur; ++l)
            if (find_par(aray[k]) == find_par(aray[l])) {
              mp[aray[k]][aray[l]]++;
              mp[aray[l]][aray[k]]++;
            }
      }
      for (int j = 0; j < v[i].size(); ++j)
        par[v[i][j].first] = par[v[i][j].second] = -1;
    }
  }
  for (int i = 1; i <= q; ++i)
    cout << ans[i] + mp[Q[i].first][Q[i].second] << endl;
  return 0;
}
