/*
ID: smg_b2
PROB: y1984
LANG: C++
*/
#include<iostream>
using namespace std;
int m,n,x[105],y[105],q,pyt[1030][1030];
void def()
{
    int i,j;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)pyt[i][j]=100000;
    }
}
int main()
{
    int a,b,r,i,j,f;
    cin>>n>>m;
    def(); 
    for(i=0;i<m;i++)
    {
        cin>>a>>b>>r;
        pyt[a][b]=r;
        pyt[b][a]=r;
    }
    cin>>q;
    for(i=0;i<q;i++)cin>>x[i]>>y[i];
    for(f=0;f<n;f++)
    {
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                if(pyt[i][f]+pyt[f][j]<pyt[i][j])pyt[i][j]=pyt[i][f]+pyt[f][j];
            }
        }
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if(pyt[i][j]!=100000)pyt[i][j]%=2;
            else pyt[i][j]=2;
            //cout<<pyt[i][j]<<" ";
        }
        //cout<<"\n";
    }
    for(i=0;i<q;i++)cout<<pyt[x[i]][y[i]]<<"\n";
    return 0;
}
