#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int>>> adjlist;
int vertices, edges, ans;
vector<int> visited;
vector<int> colorchk;
vector<vector<int>> storedans;
void print() {
  int count = 0;
  for (auto &i : adjlist) {
    cout << "For vertex " << count << endl;
    count++;
    for (auto &j : i) {
      cout << j.first << " " << j.second << endl;
    }
    cout << endl;
  }
}
void dfs(int current, int destination, int color) {
  if (colorchk[color]) return;
  if (current == destination) {
    ans++;
    colorchk[color] = 1;
    return;
  }
  visited[current] = 1;
  for (auto &i : adjlist[current]) {
    if (i.second == color && !visited[i.first]) {
      dfs(i.first, destination, color);
    }
  }
}
int main() {
  int vtx1, vtx2, color;
  cin >> vertices >> edges;
  adjlist.assign(vertices + 1, vector<pair<int, int>>());
  for (int i = 0; i < edges; i++) {
    cin >> vtx1 >> vtx2 >> color;
    adjlist[vtx1].push_back({vtx2, color});
    adjlist[vtx2].push_back({vtx1, color});
  }
  storedans.assign(vertices + 1, vector<int>());
  for (auto &i : storedans) {
    i.assign(vertices + 1, -1);
  }
  int query;
  cin >> query;
  while (query--) {
    cin >> vtx1 >> vtx2;
    if (storedans[vtx1][vtx2] != -1) {
      cout << storedans[vtx1][vtx2] << endl;
    } else {
      ans = 0;
      colorchk.assign(edges + 1, 0);
      for (auto &i : adjlist[vtx1]) {
        if (!colorchk[i.second]) {
          visited.assign(vertices + 1, 0);
          dfs(vtx1, vtx2, i.second);
        }
      }
      storedans[vtx1][vtx2] = ans;
      storedans[vtx2][vtx1] = ans;
      cout << storedans[vtx1][vtx2] << endl;
    }
  }
  return 0;
}
