#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using namespace std;
const int N = 1e5 + 2, SQ = 250;
int n, m, q, ansBig[682][682], id[N];
vector<pair<pair<int, int>, int> > edge;
vector<int> rt[N], rk[N], gCol[N], col[N], big;
int frt(int c, int i) {
  return rt[c][i] == i ? i : rt[c][i] = frt(c, rt[c][i]);
}
unordered_map<int, int> mp[N];
void buildDSU() {
  for (pair<pair<int, int>, int> E : edge) {
    int u = E.first.first, v = E.first.second, c = E.second;
    u = frt(c, mp[c][u]), v = frt(c, mp[c][v]);
    if (u != v) {
      if (rk[c][u] < rk[c][v]) swap(u, v);
      if (rk[c][u] == rk[c][v]) rk[c][u]++;
      rt[c][v] = u;
    }
  }
}
void buildBig() {
  for (int i = (0); i <= (((int)(big).size()) - 2); ++i)
    for (int c : gCol[big[i]]) {
      int u = mp[c][big[i]];
      for (int j = (i + 1); j <= (((int)(big).size()) - 1); ++j) {
        if (mp[c].find(big[j]) == mp[c].end()) continue;
        int add = (frt(c, u) == frt(c, mp[c][big[j]]));
        ansBig[i][j] += add;
        ansBig[j][i] += add;
      }
    }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n >> m;
  for (int i = (1); i <= (m); ++i) {
    int u, v, c;
    cin >> u >> v >> c;
    col[c].emplace_back(u);
    col[c].emplace_back(v);
    gCol[u].emplace_back(c);
    gCol[v].emplace_back(c);
    edge.push_back({{u, v}, c});
  }
  for (int i = (1); i <= (m); ++i)
    if (!col[i].empty()) {
      sort((col[i]).begin(), (col[i]).end());
      col[i].erase(unique((col[i]).begin(), (col[i]).end()), col[i].end());
      int nn = ((int)(col[i]).size());
      for (int j = (0); j <= (nn - 1); ++j) mp[i][col[i][j]] = j + 1;
      rt[i].assign(nn + 1, 0);
      for (int j = (1); j <= (nn); ++j) rt[i][j] = j;
      rk[i].assign(nn + 1, 0);
    }
  for (int i = (1); i <= (n); ++i)
    if (!gCol[i].empty()) {
      sort((gCol[i]).begin(), (gCol[i]).end());
      gCol[i].erase(unique((gCol[i]).begin(), (gCol[i]).end()), gCol[i].end());
      if (((int)(gCol[i]).size()) > SQ)
        id[i] = ((int)(big).size()), big.emplace_back(i);
    }
  buildDSU();
  buildBig();
  cin >> q;
  while (q--) {
    int u, v;
    cin >> u >> v;
    if (((int)(gCol[u]).size()) > ((int)(gCol[v]).size())) swap(u, v);
    if (((int)(gCol[u]).size()) <= SQ) {
      int ans = 0;
      for (int c : gCol[u]) {
        if (mp[c].find(v) == mp[c].end()) continue;
        ans += (frt(c, mp[c][u]) == frt(c, mp[c][v]));
      }
      cout << ans << '\n';
    } else
      cout << ansBig[id[u]][id[v]] << '\n';
  }
  return 0;
}
