#include <bits/stdc++.h>
using namespace std;
const long long MOD = (long long)1e9 + 7;
class DisjointSet {
 public:
  vector<long long> rank, p;
  DisjointSet() {}
  DisjointSet(long long size) {
    rank.resize(size, 0);
    p.resize(size, 0);
    for (long long i = 0; i < size; i++) makeSet(i);
  }
  void makeSet(long long x) {
    p[x] = x;
    rank[x] = 0;
  }
  bool same(long long x, long long y) { return findSet(x) == findSet(y); }
  void unite(long long x, long long y) { link(findSet(x), findSet(y)); }
  void link(long long x, long long y) {
    if (rank[x] > rank[y]) {
      p[y] = x;
    } else {
      p[x] = y;
      if (rank[x] == rank[y]) {
        rank[y]++;
      }
    }
  }
  long long findSet(long long x) {
    if (x != p[x]) {
      p[x] = findSet(p[x]);
    }
    return p[x];
  }
};
signed main() {
  long long n, m;
  cin >> n >> m;
  DisjointSet ds[m];
  for (long long i = 0; i < m; i++) ds[i] = DisjointSet(n);
  for (long long i = 0; i < m; i++) {
    long long u, v, c;
    cin >> u >> v >> c;
    u--;
    v--;
    c--;
    if (ds[c].same(u, v)) continue;
    ds[c].unite(u, v);
  }
  long long q;
  cin >> q;
  for (long long i = 0; i < q; i++) {
    long long u, v;
    cin >> u >> v;
    u--;
    v--;
    long long ans = 0;
    for (long long j = 0; j < m; j++) {
      if (ds[j].same(u, v)) ans++;
    }
    cout << ans << endl;
  }
}
