#include <bits/stdc++.h>
using namespace std;
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
bool isPath = false;
void bfsConfirm(vector<pair<int, int> > graph[], int stNode, int enNode,
                bool visited[], int color) {
  visited[stNode] = true;
  if (enNode == stNode) {
    isPath = true;
    return;
  }
  for (auto neighbours : graph[stNode]) {
    int c = neighbours.second;
    int node = neighbours.first;
    if (c == color && visited[node] == false) {
      bfsConfirm(graph, node, enNode, visited, color);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t != 0) {
    t--;
    int n, m;
    cin >> n >> m;
    vector<pair<int, int> > graph[n + 1];
    while (m != 0) {
      m--;
      int a, b, c;
      cin >> a >> b >> c;
      graph[a].push_back(make_pair(b, c));
      graph[b].push_back(make_pair(a, c));
    }
    int queries;
    cin >> queries;
    while (queries != 0) {
      queries--;
      int st, en;
      cin >> st >> en;
      set<int> answers;
      bool visited[n + 1];
      for (auto neighbours : graph[st]) {
        isPath = false;
        memset(visited, false, sizeof(visited));
        int col = neighbours.second;
        int stNode = neighbours.first;
        bfsConfirm(graph, stNode, en, visited, col);
        if (isPath == true) {
          answers.insert(col);
        }
      }
      cout << answers.size() << "\n";
    }
  }
  return 0;
}
