#include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, int> ans;
unordered_map<int, int> edge[100009];
int n, m, p[100009];
int findset(int x) { return x == p[x] ? x : p[x] = findset(p[x]); }
void unionset(int x, int y) { p[findset(x)] = findset(y); }
int main() {
  int x, y, z;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) p[i] = i;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d", &x, &y, &z);
    int tmp1 = 0, tmp2 = 0;
    if (edge[x].count(z)) tmp1 = edge[x][z];
    if (edge[y].count(z)) tmp2 = edge[y][z];
    edge[x][z] = i;
    edge[y][z] = i;
    if (tmp1) unionset(tmp1, i);
    if (tmp2) unionset(tmp2, i);
  }
  int q;
  scanf("%d", &q);
  while (q--) {
    scanf("%d%d", &x, &y);
    if (ans.count(make_pair(x, y))) {
      printf("%d\n", ans[make_pair(x, y)]);
      continue;
    } else {
      if (edge[x].size() > edge[y].size()) swap(x, y);
      z = 0;
      for (auto it = edge[x].begin(); it != edge[x].end(); ++it) {
        auto that = edge[y].find(it->first);
        if (that != edge[y].end()) {
          if (findset(it->second) == findset(that->second)) z++;
        }
      }
      printf("%d\n", z);
      ans[make_pair(x, y)] = ans[make_pair(y, x)] = z;
    }
  }
  return 0;
}
