{
TASK:Y1984
LANG:PASCAL
}

program Y1984;

const AN_UNKNOWN = 255;

var matrix:array[1..125,1..125] of Byte;
    questX,questY:array[1..100] of Byte;
    M:Word;
    N,Q:Byte;

procedure Input;
var iCall:Word;
    A,B,R:Byte;
begin
 FillChar(matrix,SizeOf(matrix),AN_UNKNOWN);
 Readln(N);
 Readln(M);
 for iCall := 1 to M do begin
  Readln(A,B,R);
  Inc(A);
  Inc(B);
  matrix[A,B] := R;
  matrix[B,A] := R;
 end;
 Readln(Q);
 for iCall := 1 to Q do begin
  Readln(questX[iCall],questY[iCall]);
  Inc(questX[iCall]);
  Inc(questY[iCall]);
 end;
end;

procedure MatrixReach;
var i,j,k:Byte;
begin
 for k := 1 to N do begin
  for i := 1 to N do begin

   If not(matrix[i,k] = AN_UNKNOWN) then begin
    for j := 1 to N do begin

     If (matrix[i,k] = 0) and (matrix[k,j] = 0) then matrix[i,j] := 0;
     If (matrix[i,k] = 0) and (matrix[k,j] = 1) then matrix[i,j] := 1;
     If (matrix[i,k] = 1) and (matrix[k,j] = 1) then matrix[i,j] := 0;
     matrix[j,i] := matrix[i,j];

    end;
   end;

  end;
 end;
end;

procedure Output;
var iQuest,X,Y:Byte;
begin
 for iQuest := 1 to Q do begin
  If (matrix[questY[iQuest],questX[iQuest]] = AN_UNKNOWN) then Writeln(2)
  else Writeln(matrix[questY[iQuest],questX[iQuest]]);
 end;
end;

begin
 Input;
 MatrixReach;
 Output;
end.