#include <bits/stdc++.h>
using namespace std;
struct color {
  map<int, bool> mp;
  vector<int> x, y, v;
} c[100005];
struct question {
  int y, i, ans;
  question(int _y, int _i, int _ans) { y = _y, i = _i, ans = _ans; }
};
vector<struct question> que[100005];
int n, m, q;
int father[100005], Rank[100005];
void init() {
  for (int i = 1; i <= n; i++) father[i] = i, Rank[i] = 0;
  for (int i = 1; i <= m; i++) {
    c[i].mp.clear();
    int sz = c[i].x.size();
    if (sz == 0) continue;
    for (int j = 0; j < sz; j++) {
      int t = c[i].x[j];
      if (c[i].mp[t] == 0) {
        c[i].mp[t] = 1;
        c[i].v.push_back(t);
      }
      t = c[i].y[j];
      if (c[i].mp[t] == 0) {
        c[i].mp[t] = 1;
        c[i].v.push_back(t);
      }
    }
  }
}
void initial(struct color &co) {
  int sizev = co.v.size();
  for (int i = 0; i < sizev; i++) {
    father[co.v[i]] = co.v[i];
    Rank[co.v[i]] = 0;
  }
}
int find_set(int x) {
  if (father[x] != x) {
    father[x] = find_set(father[x]);
  }
  return father[x];
}
void Union(int x, int y) {
  x = find_set(x);
  y = find_set(y);
  if (x != y) {
    if (Rank[x] > Rank[y])
      father[y] = x;
    else if (Rank[x] < Rank[y])
      father[x] = y;
    else {
      father[y] = x;
      Rank[x]++;
    }
  }
}
void input() {
  int x, y, color;
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &x, &y, &color);
    c[color].x.push_back(x);
    c[color].y.push_back(y);
  }
  cin >> q;
  for (int i = 0; i < q; i++) {
    scanf("%d %d", &x, &y);
    if (que[x].size() <= que[y].size())
      que[x].push_back(question(y, i, 0));
    else
      que[y].push_back(question(x, i, 0));
  }
}
void compute(int i) {
  int sz = c[i].x.size();
  for (int j = 0; j < sz; j++) Union(c[i].x[j], c[i].y[j]);
  int sizev = c[i].v.size();
  for (int j = 0; j < sizev; j++) {
    find_set(c[i].v[j]);
  }
  for (int j = 0; j < sizev; j++) {
    int t1 = c[i].v[j];
    for (int k = 0; k < que[t1].size(); k++)
      if (father[t1] == father[que[t1][k].y]) que[t1][k].ans++;
  }
}
int main() {
  scanf("%d%d", &n, &m);
  input();
  init();
  for (int i = 1; i <= m; i++) {
    if (c[i].x.size() == 0) continue;
    compute(i);
    initial(c[i]);
  }
  int ans[q + 5];
  for (int i = 1; i <= n; i++) {
    for (int j = 0; j < que[i].size(); j++) {
      ans[que[i][j].i] = que[i][j].ans;
    }
  }
  for (int i = 0; i < q; i++) printf("%d\n", ans[i]);
  return 0;
}
