#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1e5 + 5;
vector<int> changedvert;
int n, m, q;
unordered_map<long long, int> queries;
unordered_map<long long, bool> visitedq;
unordered_map<long long, bool> visitedpair;
vector<int> adjcolors[MAXN];
int par[MAXN], size[MAXN];
vector<pair<int, int> > coloredges[MAXN];
vector<pair<int, int> > query;
int answers[MAXN];
vector<int> querycolors[MAXN];
unordered_map<long long, int> queryanswers;
int find(int x) {
  if (par[x] == x) return x;
  par[x] = find(par[x]);
  return par[x];
}
void merge(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (size[x] > size[y]) swap(x, y);
  size[y] += size[x];
  par[x] = y;
}
int main() {
  for (int i = 0; i < MAXN; ++i) {
    par[i] = i;
    size[i] = 1;
    answers[i] = 0;
  }
  cin >> n >> m;
  for (int i = 0; i < m; ++i) {
    int x, y, c;
    scanf("%d%d%d", &x, &y, &c);
    coloredges[c].push_back(pair<int, int>(x, y));
    if (!visitedpair[x * MAXN + c]) {
      adjcolors[x].push_back(c);
      visitedpair[x * MAXN + c] = 1;
    }
    if (!visitedpair[y * MAXN + c]) {
      adjcolors[y].push_back(c);
      visitedpair[y * MAXN + c] = 1;
    }
  }
  cin >> q;
  for (int i = 0; i < q; ++i) {
    int x, y;
    scanf("%d%d", &x, &y);
    query.push_back(pair<int, int>(x, y));
    if (x > y) swap(x, y);
    if (visitedq[x * MAXN + y] == 1) {
      continue;
    }
    visitedq[x * MAXN + y] = 1;
    if (adjcolors[x].size() > adjcolors[y].size()) swap(x, y);
    for (int j = 0; j < adjcolors[x].size(); ++j)
      if (visitedpair.count(y * MAXN + adjcolors[x][j]))
        querycolors[adjcolors[x][j]].push_back(i);
  }
  pair<int, int> t;
  for (int i = 1; i <= (int)1e5; ++i) {
    for (int j = 0; j < coloredges[i].size(); ++j) {
      t = coloredges[i][j];
      changedvert.push_back(t.first);
      changedvert.push_back(t.second);
      merge(t.first, t.second);
    }
    for (int j = 0; j < querycolors[i].size(); ++j) {
      t = query[querycolors[i][j]];
      if (find(t.first) == find(t.second)) ++answers[querycolors[i][j]];
    }
    for (int j = 0; j < changedvert.size(); ++j) {
      size[changedvert[j]] = 1;
      par[changedvert[j]] = changedvert[j];
    }
    changedvert.clear();
  }
  for (int i = 0; i < q; ++i) {
    pair<int, int> t = query[i];
    if (t.first > t.second) swap(t.first, t.second);
    int x = max(answers[i], queryanswers[t.first * MAXN + t.second]);
    queryanswers[t.first * MAXN + t.second] = x;
    cout << x << "\n";
  }
}
