#include <bits/stdc++.h>
using namespace std;
int in() {
  int tmp;
  scanf("%d", &tmp);
  return tmp;
}
int &in(int &x) { return x = in(); }
template <typename T, typename... Args>
void in(T &x, Args &...args) {
  in(x);
  if (sizeof...(args)) in(args...);
}
template <class T, class L>
T &smax(T &x, L y) {
  if (y > x) x = y;
  return x;
}
template <class T, class L>
T &smin(T &x, L y) {
  if (y < x) x = y;
  return x;
}
const int maxn = 1e5 + 1, sq = 300;
namespace std {
template <>
struct hash<pair<int, int> > {
  size_t operator()(pair<int, int> const &x) const {
    return hash<long long>()(((long long)x.first << 32) ^ x.second);
  }
};
}  // namespace std
int n, m, cnt;
vector<pair<int, int> > ed[maxn];
vector<int> cl[maxn];
struct MCna {
  unordered_map<pair<int, int>, int> val;
  int &operator[](pair<int, int> in) { return val[in]; }
} mCna;
struct Dsu {
  int par[maxn];
  void clear() { memset(par, -1, sizeof par); }
  int r(int v) { return par[v] < 0 ? v : par[v] = r(par[v]); }
  void mrg(int v, int u) {
    if ((u = r(u)) == (v = r(v))) return;
    if (par[v] < par[u]) swap(v, u);
    par[u] += par[v], par[v] = u;
  }
} dsu[sq], tmp;
int main() {
  in(n, m);
  for (int v, u, c; m--;)
    in(v, u, c), ed[--c].push_back({--v, --u}), cl[c].push_back(v),
        cl[c].push_back(u);
  for (int i = 0; i < maxn; i++) {
    sort(cl[i].begin(), cl[i].end()),
        cl[i].resize(unique(cl[i].begin(), cl[i].end()) - cl[i].begin());
    if (cl[i].size() > sq) {
      dsu[cnt].clear();
      for (auto e : ed[i]) dsu[cnt].mrg(e.first, e.second);
      cnt++;
    } else if (cl[i].size()) {
      tmp.clear();
      for (auto e : ed[i]) tmp.mrg(e.first, e.second);
      for (int k = 0; k < cl[i].size(); k++)
        for (int j = k + 1; j < cl[i].size(); j++)
          if (tmp.r(cl[i][k]) == tmp.r(cl[i][j])) {
            mCna[minmax(cl[i][k], cl[i][j])]++;
          }
    }
  }
  int q = in();
  for (int v, u; q--;) {
    in(v, u), v--, u--;
    int ans = mCna[minmax(v, u)];
    for (int i = 0; i < cnt; i++)
      if (dsu[i].r(v) == dsu[i].r(u)) ans++;
    printf("%d\n", ans);
  }
  return 0;
}
