#include <bits/stdc++.h>
using namespace std;
template <class C>
void mini(C& a4, C b4) {
  a4 = min(a4, b4);
}
template <class C>
void maxi(C& a4, C b4) {
  a4 = max(a4, b4);
}
template <class T1, class T2>
ostream& operator<<(ostream& rout, pair<T1, T2> pair) {
  return rout << "(" << pair.first << ", " << pair.second << ")";
}
const int MX = 100100;
vector<pair<int, int> > E[MX];
vector<int> V[MX];
vector<int> out[MX];
bool vis[MX];
vector<int> fwd[MX];
vector<int> bcw[MX];
vector<int> ans[MX];
const int TH = 600;
int main() {
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < (m); ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    --a;
    --b;
    --c;
    E[c].push_back(make_pair(a, b));
    V[c].push_back(a);
    V[c].push_back(b);
  }
  int C = -1;
  for (int i = 0; i < (m); ++i) {
    for (auto p : E[i]) {
      out[p.first].push_back(p.second);
      out[p.second].push_back(p.first);
    }
    for (int v : V[i])
      if (!vis[v]) {
        queue<int> Q;
        vis[v] = true;
        ++C;
        Q.push(v);
        while (!Q.empty()) {
          int f = Q.front();
          Q.pop();
          fwd[f].push_back(C);
          bcw[C].push_back(f);
          for (int g : out[f])
            if (!vis[g]) {
              vis[g] = true;
              Q.push(g);
            }
        }
      }
    for (int v : V[i]) {
      out[v].clear();
      vis[v] = false;
    }
  }
  for (int i = 0; i < (n); ++i) {
    if (((int)(fwd[i]).size()) > TH) {
      ans[i] = vector<int>(n, 0);
      for (int c : fwd[i])
        for (int j : bcw[c]) ans[i][j]++;
    }
  }
  int q;
  cin >> q;
  for (int i = 0; i < (q); ++i) {
    int a, b;
    cin >> a >> b;
    --a;
    --b;
    if (!ans[b].empty()) swap(a, b);
    if (!ans[a].empty()) {
      cout << ans[a][b] << endl;
    } else {
      int res = 0;
      auto it = fwd[a].begin();
      auto jt = fwd[b].begin();
      while (it != fwd[a].end() && jt != fwd[b].end()) {
        if (*it < *jt)
          ++it;
        else if (*it > *jt)
          ++jt;
        else {
          ++res;
          ++it;
          ++jt;
        }
      }
      cout << res << endl;
    }
  }
  return 0;
}
