#include <bits/stdc++.h>
using namespace std;
double EPS = numeric_limits<double>::epsilon();
;
struct in {
  int c;
  int nod;
};
struct p {
  int a;
  int b;
  int c;
  bool visted;
};
int BFS(int s, int t, vector<p> w) {
  queue<in> q;
  for (int i = 0; i < w.size(); i++) {
    if (w[i].a == s) {
      w[i].visted = 1;
      in v;
      v.c = w[i].c;
      v.nod = w[i].b;
      q.push(v);
    } else if (w[i].b == s) {
      w[i].visted = 1;
      in v;
      v.c = w[i].c;
      v.nod = w[i].a;
      q.push(v);
    }
  }
  int num = 0;
  vector<int> colors;
  while (!q.empty()) {
    in r = q.front();
    q.pop();
    int j = 0;
    for (int i = 0; i < colors.size(); i++) {
      if (r.c == colors[i]) {
        j = 1;
        break;
      }
    }
    if (j) {
      continue;
    }
    if (r.nod == t) {
      num++;
      colors.push_back(r.c);
    } else {
      for (int i = 0; i < w.size(); i++) {
        if (w[i].a == r.nod && w[i].visted == 0 && w[i].c == r.c) {
          w[i].visted = 1;
          in v;
          v.c = w[i].c;
          v.nod = w[i].b;
          q.push(v);
        }
        if (w[i].b == r.nod && w[i].visted == 0 && w[i].c == r.c) {
          w[i].visted = 1;
          in v;
          v.c = w[i].c;
          v.nod = w[i].a;
          q.push(v);
        }
      }
    }
  }
  return num;
}
vector<p> w;
int main() {
  std::ios_base::sync_with_stdio(0);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    p j;
    cin >> j.a >> j.b >> j.c;
    j.visted = 0;
    w.push_back(j);
  }
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int s, t;
    cin >> s >> t;
    cout << BFS(s, t, w) << endl;
  }
  return 0;
}
