def solve(): from itertools import permutations N=int(input()) X=[None]*(N+1) for u in range(N+1): X[u]=list(map(int,input().split())) Mod=998244353 # 前計算 S=[[0]*(N+1) for _ in range(N+1)] for u in range(N+1): Su=S[u] Su[u]=1 for v in range(u,N+1): Xv=X[v] for w in range(v+1,N+1): Su[w]+=Su[v]*Xv[w] Su[w]%=Mod Q=int(input()) Ans=[0]*Q for q in range(Q): K=int(input()) A=[0]*K; B=[0]*K; C=[0]*K for k in range(K): A[k],B[k],C[k]=map(int,input().split()) for L in range(K+1): for P in permutations(range(K),r=L): temp=1; prev=0 for p in P: temp*=(S[prev][A[p]]*C[p])%Mod; temp%=Mod prev=B[p] temp*=S[prev][N]; temp%=Mod Ans[q]+=temp Ans[q]%=Mod return Ans #================================================== import sys input=sys.stdin.readline write=sys.stdout.write write("\n".join(map(str,solve())))