#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > v[500];
bool vis[500];
bool col[500];
bool f = 0;
void dfs(long long x, long long y, long long c) {
  vis[x] = true;
  if (x == y) f = 1;
  for (long long i = 0; i < v[x].size(); ++i) {
    if (!vis[v[x][i].first] && v[x][i].second == c) {
      dfs(v[x][i].first, y, c);
    }
  }
}
int main() {
  std::ios::sync_with_stdio(false);
  long long q, u, e, x, y, c, n, m;
  cin >> n >> m;
  while (m--) {
    cin >> x >> y >> c;
    v[x].push_back(make_pair(y, c));
    v[y].push_back(make_pair(x, c));
  }
  cin >> q;
  while (q--) {
    cin >> u >> e;
    long long ans = 0;
    memset(col, 0, sizeof(col));
    for (long long i = 0; i < v[u].size(); ++i) {
      f = 0;
      memset(vis, false, sizeof(vis));
      vis[u] = 1;
      if (!col[v[u][i].second]) {
        dfs(v[u][i].first, e, v[u][i].second);
        if (f) col[v[u][i].second] = 1;
        ans += f;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
