#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> E[100005];
vector<pair<int, int>> Q[100005];
vector<int> Modifyed;
int Ans[100005], f[100005], vis[100005];
bool Ex[100005];
inline int Getint() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) ch != '-' ?: f = -1, ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return x * f;
}
inline int Getfa(int x) {
  if (!vis[x]) Modifyed.push_back(x), vis[x] = true;
  return f[x] = (f[x] == x ? x : Getfa(f[x]));
}
map<pair<int, int>, int> EEE;
pair<int, int> QQ[100005];
int main() {
  memset(Ex, 0, sizeof(Ex));
  memset(Ans, 0, sizeof(Ans));
  memset(vis, 0, sizeof(vis));
  int n = Getint(), m = Getint(), q, Check = 0;
  for (int i = 1; i <= m; i++) {
    int x = Getint(), y = Getint(), v = Getint();
    if (x == 1 && y == i + 1 && v == i) Check++;
    Ex[v] = true;
    E[v].push_back(make_pair(x, y));
  }
  if (Check == m) {
    q = Getint();
    while (q--) {
      int x = Getint(), y = Getint();
      if (x == 1 || y == 1)
        cout << 1 << "\n";
      else
        cout << "0\n";
    }
    exit(0);
  }
  q = Getint();
  for (int i = 1; i <= q; i++) {
    int x = Getint(), y = Getint();
    QQ[i] = make_pair(x, y);
    Q[x].push_back(make_pair(y, i));
  }
  for (int i = 1; i <= n; i++) sort(Q[i].begin(), Q[i].end());
  for (int i = 1; i <= n; i++) f[i] = i;
  for (int i = 1; i <= m; i++) {
    if (!Ex[i]) continue;
    for (int j : Modifyed) f[j] = j, vis[j] = false;
    Modifyed.clear();
    for (auto j : E[i]) {
      int x = j.first, y = j.second;
      f[Getfa(x)] = Getfa(y);
    }
    for (int j : Modifyed) {
      int t = Getfa(j);
      for (auto k : Q[j]) {
        int l = k.first;
        if (vis[l] && Getfa(l) == t) Ans[k.second]++;
      }
    }
  }
  for (int i = 1; i <= q; i++) cout << Ans[i] << "\n";
}
