#include <bits/stdc++.h>
using namespace std;
using ii = pair<int, int>;
const int mxN = 1e5 + 5;
const int mxM = 1e5 + 5;
const int mxQ = 1e5 + 5;
const int B = sqrt(mxN);
int N, M, Q;
vector<ii> edges[mxM];
ii qry[mxN];
struct UFDS {
  vector<int> p, s;
  void init(int n) {
    p.resize(n);
    iota((p).begin(), (p).end(), 0);
    s.assign(n, 1);
  }
  int finds(int i) { return (p[i] == i) ? i : (p[i] = finds(p[i])); }
  bool unions(int i, int j) {
    int x = finds(i), y = finds(j);
    if (x == y) return 0;
    if (s[x] < s[y]) swap(x, y);
    p[y] = x, s[x] += s[y];
    return 1;
  }
  inline void reset(int i) {
    p[i] = i;
    s[i] = 1;
  }
} ufds;
bool in[mxN];
int cmap[mxN];
vector<int> smol[mxM];
set<int> big[mxM];
int scnt, bcnt;
map<ii, int> pairwise;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> N >> M;
  for (int i = (1); i <= (M); ++i) {
    int A, B, C;
    cin >> A >> B >> C;
    edges[C].emplace_back(A, B);
  }
  ufds.init(N + 1);
  bcnt = 0;
  for (int i = (1); i <= (M); ++i)
    if ((int)(edges[i]).size()) {
      vector<int> cur;
      for (auto& e : edges[i]) {
        if (!in[e.first]) cur.push_back(e.first), in[e.first] = 1;
        if (!in[e.second]) cur.push_back(e.second), in[e.second] = 1;
        ufds.unions(e.first, e.second);
      }
      scnt = 0;
      for (int& x : cur) {
        int u = ufds.finds(x);
        if (ufds.s[u] <= B) {
          if (!cmap[u]) cmap[u] = ++scnt;
          smol[cmap[u]].push_back(x);
        } else {
          if (!cmap[u]) cmap[u] = ++bcnt;
          big[cmap[u]].insert(x);
        }
      }
      for (int& x : cur) {
        cmap[ufds.finds(x)] = 0;
        in[x] = 0;
        ufds.reset(x);
      }
      for (int s = (1); s <= (scnt); ++s) {
        for (int a = (0); a <= ((int)(smol[s]).size() - 1); ++a)
          for (int b = (a + 1); b <= ((int)(smol[s]).size() - 1); ++b) {
            int U = smol[s][a], V = smol[s][b];
            if (U < V) swap(U, V);
            ++pairwise[ii(U, V)];
          }
        smol[s].clear();
      }
    }
  cin >> Q;
  for (int i = (1); i <= (Q); ++i) {
    int U, V;
    cin >> U >> V;
    if (U < V) swap(U, V);
    int ans = pairwise[ii(U, V)];
    for (int b = (1); b <= (bcnt); ++b) {
      auto x = big[b].find(U);
      if (x == big[b].end()) continue;
      auto y = big[b].find(V);
      if (y == big[b].end()) continue;
      ++ans;
    }
    cout << ans << '\n';
  }
}
