#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
unordered_map<int, int> pr[N], cnt[N];
unordered_map<int, unordered_map<int, int>> mp;
set<int> col[N];
vector<int> G[2 * N];
int n, m, q, vis[N], id, fid = 1;
int find(int c, int r) {
  if (pr[c][r] == 0) return pr[c][r] = r;
  if (pr[c][r] == r)
    return r;
  else
    return pr[c][r] = find(c, pr[c][r]);
}
void dfs(int root, int node, int c) {
  vis[node] = id;
  cnt[root][node]++;
  int h = mp[node][c];
  auto it = G[h].begin();
  auto pt = G[h].end();
  while (it != pt) {
    int go = *it;
    it++;
    if (vis[go] == id) continue;
    dfs(root, go, c);
  }
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    col[a].insert(c);
    col[b].insert(c);
    if (mp[a][c] == 0) {
      mp[a][c] = fid++;
    }
    if (mp[b][c] == 0) {
      mp[b][c] = fid++;
    }
    G[mp[a][c]].push_back(b);
    G[mp[b][c]].push_back(a);
    int u = find(c, a);
    int v = find(c, b);
    if (u != v) {
      pr[c][u] = pr[c][v];
    }
  }
  int sq = sqrt(m) / 2;
  for (int i = 1; i <= n; i++) {
    if (col[i].size() < sq) continue;
    for (int j : col[i]) {
      ++id;
      dfs(i, i, j);
    }
  }
  scanf("%d", &q);
  while (q--) {
    int a, b, ans = 0;
    scanf("%d %d", &a, &b);
    if (col[a].size() > col[b].size()) swap(a, b);
    if (col[a].size() < sq) {
      for (int i : col[a])
        if (find(i, a) == find(i, b)) ans++;
    } else {
      ans = cnt[a][b];
    }
    printf("%d\n", ans);
  }
}
