#include <bits/stdc++.h>
using namespace std;
int n, m, q;
map<int, int> f[111111];
vector<pair<int, int> > g[111111];
map<pair<int, int>, int> ans;
int F(int ind, int x) {
  if (!f[ind].count(x) || f[ind][x] == x) return f[ind][x] = x;
  return f[ind][x] = F(ind, f[ind][x]);
}
void M(int c, int a, int b) {
  a = F(c, a);
  b = F(c, b);
  if (rand() % 2) swap(a, b);
  f[c][a] = b;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    a--;
    b--;
    c--;
    M(c, a, b);
  }
  for (int i = 0; i < m; i++) {
    for (map<int, int>::iterator itr = f[i].begin(); itr != f[i].end(); itr++) {
      g[itr->first].push_back({i, F(i, itr->first)});
    }
  }
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    a--;
    b--;
    if (g[a].size() > g[b].size()) swap(a, b);
    if (ans.count({a, b})) {
      printf("%d\n", ans[{a, b}]);
      continue;
    }
    int res = 0;
    for (int i = 0; i < g[a].size(); i++) {
      if (binary_search(g[b].begin(), g[b].end(), g[a][i])) res++;
    }
    printf("%d\n", ans[{a, b}] = ans[{b, a}] = res);
  }
  return 0;
}
