#include <bits/stdc++.h>
using namespace std;
const int N = 100010, S = 320;
vector<pair<int, int> > edge[N];
vector<int> ver[N];
vector<int> Small, Big;
map<int, int> res[N];
int n, m, q, lab[N];
struct dsu {
  vector<int> par;
  dsu(int sz = 0) {
    par.assign(sz + 1, 1);
    for (int i = 1; i <= sz; i++) par[i] = i;
  }
  int anc(int p) { return p == par[p] ? p : par[p] = anc(par[p]); }
  void join(int p, int q) {
    int x = anc(p), y = anc(q);
    if (x != y) par[x] = y;
  }
} M[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v, c;
    cin >> u >> v >> c;
    if (u > v) swap(u, v);
    edge[c].push_back(pair<int, int>(u, v));
    ver[c].push_back(u);
    ver[c].push_back(v);
  }
  for (int i = 1; i <= m; i++)
    if (edge[i].size() > S)
      Big.push_back(i);
    else if (edge[i].size())
      Small.push_back(i);
  for (int i = 1; i <= m; i++) {
    sort(ver[i].begin(), ver[i].end());
    ver[i].resize(
        distance(ver[i].begin(), unique(ver[i].begin(), ver[i].end())));
  }
  for (int i = 0; i < Big.size(); i++) {
    int c = Big[i];
    M[c] = dsu(n);
    for (int j = 0; j < edge[c].size(); j++)
      M[c].join(edge[c][j].first, edge[c][j].second);
  }
  for (int i = 0; i < Small.size(); i++) {
    int c = Small[i];
    M[c] = dsu(ver[c].size());
    for (int j = 0; j < ver[c].size(); j++) lab[ver[c][j]] = j + 1;
    for (int j = 0; j < edge[c].size(); j++) {
      int u = edge[c][j].first, v = edge[c][j].second;
      M[c].join(lab[u], lab[v]);
    }
    for (int j = 0; j < ver[c].size() - 1; j++)
      for (int k = j + 1; k < ver[c].size(); k++) {
        int u = ver[c][j], v = ver[c][k];
        int x = M[c].anc(j + 1), y = M[c].anc(k + 1);
        if (x == y) res[u][v]++;
      }
    for (int j = 0; j < ver[c].size(); j++) lab[ver[c][j]] = 0;
  }
  cin >> q;
  while (q--) {
    int u, v;
    cin >> u >> v;
    if (u > v) swap(u, v);
    int ans = 0;
    for (int i = 0; i < Big.size(); i++)
      if (M[Big[i]].anc(u) == M[Big[i]].anc(v)) ++ans;
    if (res[u].count(v)) ans += res[u][v];
    cout << ans << endl;
  }
}
