#include <bits/stdc++.h>
using namespace std;
clock_t __stt;
inline void TStart() { __stt = clock(); }
inline void TReport() {
  printf("\nTaken Time : %.3lf sec\n",
         (double)(clock() - __stt) / CLOCKS_PER_SEC);
}
template <typename T>
T MIN(T a, T b) {
  return a < b ? a : b;
}
template <typename T>
T MAX(T a, T b) {
  return a > b ? a : b;
}
template <typename T>
T ABS(T a) {
  return a > 0 ? a : (-a);
}
template <typename T>
void UMIN(T &a, T b) {
  if (b < a) a = b;
}
template <typename T>
void UMAX(T &a, T b) {
  if (b > a) a = b;
}
const int buc = 320;
vector<pair<int, int> > cols[100005];
vector<int> adj[100005], parts[100005], in[100005];
int n, m, q, cnt, bct, inc[100005], id[100005], ans[500][100005];
bool vis[100005];
void bfs(int ver, int col) {
  int i;
  queue<int> Q;
  while (!Q.empty()) Q.pop();
  vis[ver] = 1;
  Q.push(ver);
  while (!Q.empty()) {
    int cv = Q.front();
    Q.pop();
    ++inc[cv];
    parts[col].push_back(cv);
    for (i = 0; i < (int)adj[cv].size(); ++i) {
      if (!vis[adj[cv][i]]) {
        vis[adj[cv][i]] = 1;
        Q.push(adj[cv][i]);
      }
    }
  }
}
int main() {
  scanf("%d %d", &n, &m);
  memset(id, -1, sizeof(id));
  int i, j, k, a, b, c;
  for (i = 0; i < m; ++i) {
    scanf("%d %d %d", &a, &b, &c);
    --a;
    --b;
    cols[c].push_back(make_pair(a, b));
  }
  for (i = 1; i <= m; ++i) {
    for (j = 0; j < cols[i].size(); ++j) {
      adj[cols[i][j].first].push_back(cols[i][j].second);
      adj[cols[i][j].second].push_back(cols[i][j].first);
    }
    memset(vis, 0, sizeof(vis));
    for (j = 0; j < (int)cols[i].size(); ++j) {
      if (!vis[cols[i][j].first]) bfs(cols[i][j].first, cnt++);
    }
    for (j = 0; j < cols[i].size(); ++j) {
      adj[cols[i][j].first].clear();
      adj[cols[i][j].second].clear();
    }
  }
  for (i = 0; i < n; ++i) {
    if (inc[i] >= buc) {
      id[i] = bct++;
    }
  }
  for (i = 0; i < cnt; ++i) {
    for (j = 0; j < parts[i].size(); ++j) {
      in[parts[i][j]].push_back(i);
      if (id[parts[i][j]] >= 0) {
        for (k = 0; k < parts[i].size(); ++k)
          ans[id[parts[i][j]]][parts[i][k]]++;
      }
    }
  }
  for (i = 0; i < n; ++i) sort(in[i].begin(), in[i].end());
  scanf("%d", &q);
  while (q--) {
    scanf("%d %d", &a, &b);
    --a;
    --b;
    if (id[a] == -1) swap(a, b);
    if (id[a] == -1) {
      i = j = k = 0;
      while (j < in[a].size() && k < in[b].size()) {
        while (j < in[a].size() && in[a][j] < in[b][k]) ++j;
        while (k < in[b].size() && in[b][k] < in[a][j]) ++k;
        if (j < in[a].size() && k < in[b].size() && in[a][j] == in[b][k]) {
          ++i;
          ++j;
          ++k;
        }
      }
      printf("%d\n", i);
    } else {
      printf("%d\n", ans[id[a]][b]);
    }
  }
  return 0;
}
