#include <bits/stdc++.h>
using namespace std;
const int N = 4e5;
struct Ask {
  int x, y, id;
} ask[N];
vector<int> edge[N];
vector<int>::iterator it;
map<int, int> getpos[N];
int du[N], u[N], v[N], c[N], ans[N], f[N];
int ff(const int &x) {
  if (f[x] == x) return x;
  f[x] = ff(f[x]);
  return f[x];
}
int cmp(const Ask &a, const Ask &b) {
  if (a.x != b.x) return a.x < b.x;
  return a.y < b.y;
}
int main() {
  int n, m;
  cin >> n >> m;
  memset(du, 0, sizeof(du));
  int numpos = 0;
  for (int i = 1; i <= 3e5; i++) f[i] = i;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d", &u[i], &v[i], &c[i]);
    if (getpos[c[i]].find(u[i]) == getpos[c[i]].end()) {
      numpos++;
      getpos[c[i]][u[i]] = numpos;
    }
    if (getpos[c[i]].find(v[i]) == getpos[c[i]].end()) {
      numpos++;
      getpos[c[i]][v[i]] = numpos;
    }
    edge[u[i]].push_back(c[i]);
    edge[v[i]].push_back(c[i]);
  }
  for (int i = 1; i <= n; i++) {
    sort(edge[i].begin(), edge[i].end());
    edge[i].erase(unique(edge[i].begin(), edge[i].end()), edge[i].end());
    du[i] = edge[i].size();
  }
  for (int i = 1; i <= m; i++) {
    int x = getpos[c[i]][u[i]], y = getpos[c[i]][v[i]];
    f[ff(x)] = ff(y);
  }
  int numq;
  cin >> numq;
  for (int i = 1; i <= numq; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    ask[i] = Ask{min(x, y), max(x, y), i};
  }
  sort(ask + 1, ask + numq + 1, cmp);
  ask[0] = Ask{0, 0, 0};
  int lastans = 0;
  for (int i = 1; i <= numq; i++)
    if (ask[i].x == ask[i - 1].x && ask[i].y == ask[i - 1].y)
      ans[ask[i].id] = lastans;
    else {
      int x = ask[i].x, y = ask[i].y;
      if (du[x] > du[y]) swap(x, y);
      for (it = edge[x].begin(); it != edge[x].end(); it++) {
        int c = *it;
        if (getpos[c].find(y) != getpos[c].end()) {
          if (ff(getpos[c][x]) == ff(getpos[c][y])) ans[ask[i].id]++;
        }
      }
      lastans = ans[ask[i].id];
    }
  for (int i = 1; i <= numq; i++) printf("%d\n", ans[i]);
}
