#include <bits/stdc++.h>
using namespace std;
int X[] = {1, -1, 0, 0};
int Y[] = {0, 0, 1, -1};
const int N = 2e5 + 5;
int n, m, q;
vector<vector<int> > graph(101);
map<pair<int, int>, vector<int> > clr;
vector<vector<int> > ans(101, vector<int>(101, 0));
void bfs(int pos) {
  queue<int> q;
  q.push(pos);
  vector<vector<int> > color(n + 1, vector<int>(m + 1));
  for (int i = 1; i <= m; i++) color[pos][i] = 1;
  vector<int> vis(n + 1, 0);
  vis[pos] = 1000;
  int now = 101;
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    for (int to : graph[u]) {
      int cnt = 0;
      vector<int> tmp = clr[make_pair(min(to, u), max(to, u))];
      for (auto it : tmp) (color[u][it] == 1) ? color[to][it] = 1 : 1;
      for (int i = 1; i <= m; i++) {
        if (color[to][i]) cnt++;
      }
      if (vis[to] < cnt) {
        vis[to] = cnt;
        q.push(to);
      }
    }
  }
  for (int i = 1; i <= n; i++) ans[i][pos] = ans[pos][i] = vis[i];
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n >> m;
  int a, b, c;
  for (int i = 0; i < m; i++) {
    cin >> a >> b >> c;
    graph[a].push_back(b);
    graph[b].push_back(a);
    if (a > b) swap(a, b);
    clr[make_pair(a, b)].push_back(c);
  }
  for (int i = 1; i <= n; i++) bfs(i);
  cin >> q;
  while (q--) {
    cin >> a >> b;
    cout << ans[a][b] << endl;
  }
}
