#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 30, Mod = 1e9 + 7;
const long long SQ = 330;
unordered_map<int, int> Par[N];
map<pair<int, int>, int> ans;
vector<int> G[N];
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int find(int x, int c) {
  if (Par[c].find(x) == Par[c].end()) return x;
  return Par[c][x] = find(Par[c][x], c);
}
inline void merge(int x, int y, int c) {
  x = find(x, c);
  y = find(y, c);
  if (x == y) return;
  Par[c][x] = y;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    G[a].push_back(c);
    G[b].push_back(c);
    merge(a, b, c);
  }
  for (int i = 1; i <= n; i++) {
    sort(G[i].begin(), G[i].end());
    G[i].resize(unique(G[i].begin(), G[i].end()) - G[i].begin());
  }
  int q;
  cin >> q;
  while (q--) {
    int a, b;
    cin >> a >> b;
    if (G[a].size() > G[b].size()) swap(a, b);
    if (G[a].size() == G[b].size() and a > b) swap(a, b);
    if (ans.count({a, b})) {
      cout << ans[{a, b}] << '\n';
      continue;
    }
    int res = 0;
    for (auto u : G[a])
      if (find(b, u) == find(a, u)) res++;
    ans[{a, b}] = res;
    cout << res << '\n';
  }
  return (0);
}
