#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int M = 1e5 + 1;
map<int, vector<int>> vec[M];
map<int, int> mp[M], is[M];
map<pair<int, int>, int> ans;
int cnt;
void dfs(int v, int col) {
  mp[v][col] = cnt;
  for (int u : vec[v][col])
    if (!mp[u].count(col)) dfs(u, col);
}
int siz(int v) { return vec[v].size(); }
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    is[a][c] = 1;
    is[b][c] = 1;
    vec[a][c].push_back(b);
    vec[b][c].push_back(a);
  }
  for (int i = 1; i <= n; i++)
    for (auto v : is[i])
      if (!mp[i].count(v.first)) cnt++, dfs(i, v.first);
  int q;
  cin >> q;
  while (q--) {
    int v, u;
    scanf("%d%d", &v, &u);
    if (ans.count({v, u})) {
      printf("%d\n", ans[{v, u}]);
      continue;
    }
    if (u > v) swap(v, u);
    if (siz(u) > siz(v)) swap(v, u);
    int curr = 0;
    for (auto c : mp[u])
      if (is[v].count(c.first) && c.second == mp[v][c.first]) curr++;
    printf("%d\n", ans[{v, u}] = ans[{u, v}] = curr);
  }
}
