#include <bits/stdc++.h>
const int N = 100000 + 5;
int n, m, q;
int stamp;
int fa[N], vis[N], answer[N];
std::pair<int, int> queries[N];
std::map<std::pair<int, int>, int> count;
std::vector<std::pair<int, int> > colors[N];
int find(int u) { return fa[u] == u ? u : fa[u] = find(fa[u]); }
void work() {
  stamp = 0;
  for (int k = 0; k < m; k++) {
    if ((int)colors[k].size() == 0) {
      continue;
    }
    std::vector<int> buffer(0);
    for (int i = 0; i < (int)colors[k].size(); i++) {
      buffer.push_back(colors[k][i].first);
      buffer.push_back(colors[k][i].second);
    }
    std::sort(buffer.begin(), buffer.end());
    buffer.erase(std::unique(buffer.begin(), buffer.end()), buffer.end());
    stamp++;
    for (int i = 0; i < (int)buffer.size(); i++) {
      int u = buffer[i];
      fa[u] = u;
      vis[u] = stamp;
    }
    for (int i = 0; i < (int)colors[k].size(); i++) {
      int u = find(colors[k][i].first);
      int v = find(colors[k][i].second);
      if (u != v) {
        fa[u] = v;
      }
    }
    if (1ll * buffer.size() * buffer.size() > n) {
      for (int i = 0; i < q; i++) {
        int u = queries[i].first;
        int v = queries[i].second;
        if (vis[u] == stamp && vis[v] == stamp) {
          answer[i] += find(u) == find(v);
        }
      }
    } else {
      for (int i = 0; i < (int)buffer.size(); i++) {
        for (int j = i + 1; j < (int)buffer.size(); j++) {
          int u = buffer[i], v = buffer[j];
          if (find(u) == find(v)) {
            count[std::make_pair(u, v)]++;
            count[std::make_pair(v, u)]++;
          }
        }
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    int u, v, w;
    scanf("%d%d%d", &u, &v, &w);
    u--, v--, w--;
    colors[w].push_back({u, v});
  }
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--, v--;
    queries[i] = {u, v};
  }
  work();
  for (int i = 0; i < q; i++) {
    printf(
        "%d\n",
        answer[i] + count[std::make_pair(queries[i].first, queries[i].second)]);
  }
  return 0;
}
