mod = 998244353 n = int(input()) x = [list(map(int, input().split())) for _ in range(n+1)] # 初期の辺だけでの pre = [[0]*(n+1) for _ in range(n+1)] for i in range(n+1): pre[i][i] = 1 for j in range(i+1, n+1): for k in range(i, j): pre[i][j] += pre[i][k]*x[k][j]%mod pre[i][j] %= mod q = int(input()) for _ in range(q): k = int(input()) abc = [list(map(int, input().split())) for _ in range(k)] abc.sort(key=lambda x: x[1]) # dp[i]...最後に使った辺がabc[i]のときのパスの数 dp = [0]*k # 追加の辺を使わない場合を予め答えに足しておく ans = pre[0][n] for i in range(k): a, b, c = abc[i] dp[i] = pre[0][a] for j in range(i): p = abc[j][1] dp[i] += dp[j]*pre[p][a]%mod dp[i] *= c dp[i] %= mod # これ以上追加の辺を使わない場合を答えに足す ans += dp[i]*pre[b][n]%mod ans %= mod print(ans)