#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const int SZ = 100005;
vector<int> comp[SZ];
vector<int> rang[SZ];
vector<int> vert[SZ];
unordered_map<int, int> dict[SZ];
struct q {
  int a, b, c;
  q(int g = 0, int h = 0, int u = 0) {
    a = g;
    b = h;
    c = u;
  }
};
int get_comp(int i, int a) {
  if (comp[i][a] == a) {
    return a;
  }
  return comp[i][a] = get_comp(i, comp[i][a]);
}
void comp_union(int i, int a, int b) {
  int x = get_comp(i, a), y = get_comp(i, b);
  if (x == y) {
    return;
  }
  if (rang[x] < rang[y]) {
    swap(x, y);
  }
  comp[i][y] = x;
  if (rang[i][x] == rang[i][y]) {
    rang[i][x]++;
  }
}
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  set<int> color[n];
  q graph[m];
  for (int i = 0; i < m; ++i) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    --a;
    --b;
    --c;
    color[a].insert(c);
    color[b].insert(c);
    vert[c].push_back(a);
    vert[c].push_back(b);
    graph[i] = q(a, b, c);
  }
  for (int i = 0; i < SZ; ++i) {
    int c = 0;
    for (auto j : vert[i]) {
      if (dict[i].find(j) == dict[i].end()) {
        dict[i][j] = c;
        ++c;
      }
    }
    rang[i].resize(c, 1);
    for (int j = 0; j < c; ++j) {
      comp[i].push_back(j);
    }
  }
  for (auto i : graph) {
    comp_union(i.c, dict[i.c][i.a], dict[i.c][i.b]);
  }
  int k;
  map<pair<int, int>, int> res;
  scanf("%d", &k);
  for (int i = 0; i < k; ++i) {
    int a, b;
    scanf("%d%d", &a, &b);
    --a;
    --b;
    if (res.find({a, b}) != res.end()) {
      printf("%d\n", res[{a, b}]);
      continue;
    }
    if (res.find({b, a}) != res.end()) {
      printf("%d\n", res[{b, a}]);
      continue;
    }
    int ans = 0;
    if (color[a].size() > color[b].size()) {
      swap(a, b);
    }
    for (auto c : color[a]) {
      if (dict[c].find(b) == dict[c].end()) {
        continue;
      }
      if (dict[c].find(a) == dict[c].end()) {
        continue;
      }
      if (get_comp(c, dict[c][a]) == get_comp(c, dict[c][b])) {
        ++ans;
      }
    }
    res[{a, b}] = ans;
    printf("%d\n", ans);
  }
  return 0;
}
