/*
TASK: Y1984.cpp
LANG: C
*/
#include<iostream>
using namespace std;

int P[1028][1028]={-1},V[128][3];

int main()
{ int n , m , a , b , r , q ;
  cin >> n >> m;
 for ( int  s=0 ; s<m ; s++)
  {
  cin >> a >> b >> r ;
   P[a][b]=r ; P[b][a]=r ;
  }

 for ( int j=0 ; j<=n ; j++ )
  for ( int i=0 ; i<=n ; i++ )
    {
     if ( !P[j][i] )
      for ( int t=0 ; t<=n ; t++ )
              {
              if( !P[i][t] )
               P[j][t]=0 ;
              if( !P[j][t] )
               P[i][t]=0 ;
              }
     }
cin >> q ;
 for ( int i=0 ; i<q ; i++ )
  cin >> V[i][1] >> V[i][2];
 for ( int j1=0 ; j1<q ; j1++ )
 {
  if ( P [ V[j1][1] ] [ V[j1][2] ]==-1 ) cout << 2 << endl;
  else
   cout << P [ V[j1][1] ] [ V[j1][2] ] << endl ;
 }
return 0;
}
