#include #ifdef LOCAL #include #else #define debug(...) void(0) #endif #include "atcoder/modint" using namespace std; typedef long long ll; #define all(x) begin(x), end(x) constexpr int INF = (1 << 30) - 1; constexpr long long IINF = (1LL << 60) - 1; constexpr int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; template istream& operator>>(istream& is, vector& v) { for (auto& x : v) is >> x; return is; } template ostream& operator<<(ostream& os, const vector& v) { auto sep = ""; for (const auto& x : v) os << exchange(sep, " ") << x; return os; } template bool chmin(T& x, U&& y) { return y < x and (x = forward(y), true); } template bool chmax(T& x, U&& y) { return x < y and (x = forward(y), true); } template void mkuni(vector& v) { sort(begin(v), end(v)); v.erase(unique(begin(v), end(v)), end(v)); } template int lwb(const vector& v, const T& x) { return lower_bound(begin(v), end(v), x) - begin(v); } using mint = atcoder::modint998244353; struct edge { int u, v, w; edge(int u, int v, int w) : u(u), v(v), w(w) {} bool operator<(const edge& rhs) const { return u < rhs.u; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector X(N + 1, vector(N + 1)); for (int i = 0; i <= N; i++) { for (int j = 0; j <= N; j++) { cin >> X[i][j]; } } vector dp(N + 1, vector(N + 1, 0)); for (int i = 0; i <= N; i++) { dp[i][i] = 1; for (int j = i; j <= N; j++) { mint& val = dp[i][j]; for (int k = 0; k <= N; k++) dp[i][k] += val * X[j][k]; } } auto query = [&](vector& es) -> mint { vector cand; cand.emplace_back(0); cand.emplace_back(N); for (auto& e : es) { cand.emplace_back(e.u); cand.emplace_back(e.v); } mkuni(cand); int n = cand.size(); vector> out(n); for (auto& e : es) { e.u = lwb(cand, e.u); e.v = lwb(cand, e.v); out[e.u].emplace_back(e); } vector d(n, 0); d[0] = 1; mint res = 0; for (int i = 0; i < n; i++) { mint sum = 0; for (int j = 0; j <= i; j++) sum += d[j] * dp[cand[j]][cand[i]]; for (auto& e : out[i]) d[e.v] += sum * e.w; res += d[i] * dp[cand[i]][N]; } return res; }; int Q; cin >> Q; for (; Q--;) { int K; cin >> K; vector es; for (int i = 0; i < K; i++) { int A, B, C; cin >> A >> B >> C; es.emplace_back(A, B, C); } cout << query(es).val() << '\n'; } return 0; }