{
task: y1984
lang: pascal
}
Program lqlq;
 type   mas=array[1..1024,1..3]of longint;
        t=array[1..1024]of longint;
  var
        i,j,m,n,q:longint;
        a:mas;
        b:t;
        c,k:longint;

 Begin
  read(n);
  read(m);
  for i:=1 to m do
        for j:=1 to 3 do
                read(a[i,j]);
  read(q);
  for k:=1 to (2*q) do
        read(b[k]);
  k:=1;
  c:=(2*q)+1;
  repeat
        if b[k]=0 then begin
                i:=1;
                b[c]:=a[i,3];
                inc(c);
                inc(k);
            end
           else begin
                        i:=b[k];
                        b[c]:=a[i,3];
                        inc(c);
                        inc(k);
                end;
  until k=(2*q)+1;
  if c=(2*q)+4 then
        begin
                b[c]:=b[c]+b[c+1]+b[c+2];
                if b[c]=2 then
                        write('0');
                if b[c]=1 then
                        write('1');
        end;
  if c=(2*q)+5 then
        begin
                b[c]:=b[c]+b[c+1]+b[c+2]+b[c+3];
                if b[c]=2 then
                        write('0');
                if b[c]=1 then
                        write('1');
        end;
  if (c<>2*q+4) and (c<>2*q+5) then
        write('2');
  end.















