#include <bits/stdc++.h>
using namespace std;
inline void in(int &x) {
  x = 0;
  char c = getchar();
  while (c < '0' || c > '9') c = getchar();
  while (c >= '0' && c <= '9')
    x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
}
int n, m, tot, fa[320][100005], tmp_fa[100005], colorc, q, tag[100005],
    tmp[100005];
vector<pair<int, int> > color[100005];
vector<int> v[100005];
map<pair<int, int>, int> res;
int Find(int Fa[], int x) { return x == Fa[x] ? x : Fa[x] = Find(Fa, Fa[x]); }
void dfs(int from, int c) {
  tag[from] = c;
  for (int i = 0; i < v[from].size(); ++i) {
    int to = v[from][i];
    if (tag[to]) continue;
    dfs(to, c);
  }
}
int main() {
  in(n);
  in(m);
  for (int i = 0; i < m; ++i) {
    int x, y, c;
    in(x);
    in(y);
    in(c);
    color[c].push_back(make_pair(x, y));
  }
  for (int c = 1; c <= m; ++c)
    if (color[c].size() >= n - 1)
      ++tot;
    else if (color[c].size() >= 320) {
      for (int j = 1; j <= n; ++j) fa[colorc][j] = j;
      for (int j = 0; j < color[c].size(); ++j) {
        int x = color[c][j].first, y = color[c][j].second;
        int xx = Find(fa[colorc], x), yy = Find(fa[colorc], y);
        if (xx != yy) fa[colorc][xx] = yy;
      }
      for (int j = 1; j <= n; ++j) fa[colorc][j] = Find(fa[colorc], j);
      ++colorc;
    } else if (color[c].size()) {
      int tmpc = 0;
      for (int j = 0; j < color[c].size(); ++j) {
        int x = color[c][j].first, y = color[c][j].second;
        tmp[tmpc++] = x, tmp[tmpc++] = y;
      }
      sort(tmp, tmp + tmpc);
      int sz = unique(tmp, tmp + tmpc) - tmp;
      for (int i = 0; i < sz; ++i) tmp_fa[tmp[i]] = tmp[i];
      for (int i = 0; i < color[c].size(); ++i) {
        int x = color[c][i].first, y = color[c][i].second;
        int xx = Find(tmp_fa, x), yy = Find(tmp_fa, y);
        if (xx != yy) tmp_fa[xx] = yy;
      }
      for (int i = 0; i < sz; ++i)
        for (int j = i + 1; j < sz; ++j)
          if (Find(tmp_fa, tmp[i]) == Find(tmp_fa, tmp[j]))
            res[make_pair(min(tmp[i], tmp[j]), max(tmp[i], tmp[j]))]++;
    }
  in(q);
  map<pair<int, int>, int>::iterator it;
  while (q--) {
    int x, y, ans;
    in(x);
    in(y);
    it = res.find(make_pair(min(x, y), max(x, y)));
    if (it == res.end())
      ans = tot;
    else
      ans = tot + it->second;
    for (int i = 0; i < colorc; ++i) ans += fa[i][x] == fa[i][y];
    printf("%d\n", ans);
  }
  return 0;
}
