#include <bits/stdc++.h>
using namespace std;
int n, m, q;
vector<int> colors[100013];
unordered_map<int, vector<int> > adj[100013];
unordered_map<int, int> p[100013];
unordered_map<int, int> h[100013];
pair<int, int> visited[100013];
unordered_map<int, int> precalc[100013];
int BIG = 200;
int findSet(int x, int c) {
  return p[x][c] == x ? x : p[x][c] = findSet(p[x][c], c);
}
void mergeSet(int a, int b, int c) {
  int r1 = findSet(a, c), r2 = findSet(b, c);
  if (r1 != r2) {
    if (h[r1][c] < h[r2][c])
      p[r1][c] = r2;
    else if (h[r1][c] > h[r2][c])
      p[r2][c] = r1;
    else
      p[r1][c] = r2, h[r2][c] += 1;
  }
}
bool sameSet(int a, int b, int c) { return findSet(a, c) == findSet(b, c); }
void dfs(int x, int c, int start) {
  visited[x] = make_pair(start + 1, c);
  precalc[start][x] += 1;
  for (int i = 0; i < adj[x][c].size(); i++)
    if (visited[adj[x][c][i]] != make_pair(start + 1, c))
      dfs(adj[x][c][i], c, start);
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    a -= 1;
    b -= 1;
    if (!p[a].count(c)) p[a][c] = a, h[a][c] = 0, colors[a].push_back(c);
    if (!p[b].count(c)) p[b][c] = b, h[b][c] = 0, colors[b].push_back(c);
    mergeSet(a, b, c);
    adj[a][c].push_back(b);
    adj[b][c].push_back(a);
  }
  for (int i = 0; i < n; i++)
    if (colors[i].size() >= BIG)
      for (int j = 0; j < colors[i].size(); j++) dfs(i, colors[i][j], i);
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    u -= 1;
    v -= 1;
    if (colors[u].size() >= BIG)
      printf("%d\n", precalc[u][v]);
    else if (colors[v].size() >= BIG)
      printf("%d\n", precalc[v][u]);
    else {
      int ans = 0;
      if (colors[u].size() < colors[v].size()) {
        for (int i = 0; i < colors[u].size(); i++)
          if (p[v].count(colors[u][i]) && sameSet(u, v, colors[u][i])) ans += 1;
      } else
        for (int i = 0; i < colors[v].size(); i++)
          if (p[u].count(colors[v][i]) && sameSet(u, v, colors[v][i])) ans += 1;
      printf("%d\n", ans);
    }
  }
  return 0;
}
