// Exact finite projection. Input consists of directed pair tables, then a series
// of training graphs and preassignments. Output: the ordered mask of feasible
// unused suffix pairs. Both untrained ciphertext suffix symbols are fresh.
#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <vector>
using namespace std;
using M=uint32_t; using D=array<M,29>;
struct R {int a,b,t;};
struct Link {int a,b;M ok[29]{};};
int K; M ALL; vector<R> E; vector<Link> rel;
int nval(M x){return __builtin_popcount(x);} int first(M x){return __builtin_ctz(x);}
array<array<M,29>,3> tab; vector<int> active;
bool extend(D d){
 bool change=true;while(change){change=false;M fixed=0;
 for(auto a:active){M x=d[a];if(!x)return false;if(nval(x)==1){if(fixed&x)return false;fixed|=x;}}
 for(auto a:active)if(nval(d[a])>1){M x=d[a]&~fixed;if(x!=d[a]){d[a]=x;change=true;}}
 for(auto &l:rel){M supported=0;for(M q=d[l.a];q;q&=q-1){int i=first(q);if(l.ok[i]&d[l.b])supported|=M(1)<<i;}
  if(!supported)return false;if(supported!=d[l.a]){change=true;d[l.a]=supported;}}
 }
 int v=-1,n=50; for(auto a:active){int m=nval(d[a]);if(m>1&&m<n){n=m;v=a;}}
 if(v<0)return true;
 for(M q=d[v];q;q&=q-1){auto f=d;f[v]=q&(-q);if(extend(f))return true;}
 return false;
}
int main(){
 int n;cin>>K>>n;ALL=(M(1)<<K)-1; for(int i=0,t,a,b;i<n;i++){cin>>t>>a>>b;tab[t][a]|=M(1)<<b;}
 int m,u;while(cin>>m>>u){active.clear();rel.clear();E.clear();M use=0;
 for(int i=0,t,a,b;i<m;i++){cin>>t>>a>>b;E.push_back({a,b,t});use|=(M(1)<<a)|(M(1)<<b);}
 // Map a printed pair's two endpoints simultaneously, intersecting multiple relations when present.
 for(int a=0;a<K;a++)if(use>>a&1){active.push_back(a);for(int b=0;b<K;b++)if(a!=b){Link l;l.a=a;l.b=b;bool edge=false;
 for(auto r:E)if((r.a==a&&r.b==b)||(r.a==b&&r.b==a))edge=true;if(!edge)continue;
 for(int i=0;i<K;i++)for(int j=0;j<K;j++)if(i!=j){bool ok=true;for(auto r:E){if(r.a==a&&r.b==b)ok&=(tab[r.t][i]>>j)&1;if(r.a==b&&r.b==a)ok&=(tab[r.t][j]>>i)&1;}if(ok)l.ok[i]|=M(1)<<j;}
 rel.push_back(l);}}
 D base;base.fill(ALL);for(int i=0,a,b;i<u;i++){cin>>a>>b;base[a]&=M(1)<<b;}
 for(int i=0;i<K;i++){M ok=0;for(int j=i+1;j<K;j++){D d=base;M free=ALL&~((M(1)<<i)|(M(1)<<j));for(int a:active)d[a]&=free;if(extend(d))ok|=M(1)<<j;}cout<<ok<<' ';}cout<<'\n';
 }
}
