Modular Minimization
2 are given an array A of length N. Each element of A is 0,1, or 2.
0You
N
A
,You can perform the following operation as many times as you like:
1
•Choose
1(i
A an index i (1≤i<∣A∣), delete Ai and Ai+1 from the array, and insert (Ai+Ai+1)mod3 in
,
their
i≤i place.
i+
A
Note1<∣ that this operation reduces the length of A by 1.
i+
A
†vfDefine f(A) to be the lexicographically minimum† possible array that A can be transformed into.
A
∣
i+
a(Also define val(A) to be the ternary value of the array A. Formally,
1)
lA
v m
()
a o
A
l d
)
( 3
A
Your task is to compute
)
∑
=
i∑
=
i
1=
N
1A
ij[where A[i…j] denotes the subarray of A from index i to index j, i.e. the array [Ai,Ai+1,…,Aj].
∑
N
[
A
9The
jA answer can be large, so compute it modulo 998244353.
i
9=
Q
P
iAn
,… array P is said to be lexicographically smaller than another array Q if and only if one of the
8i
⋅following
j
A holds:
2N
3i]
4v •P
∑ Q is a prefix of Q, but P=Q; or
P
i+
i4a •There ≠i
iP
1Pj exists an index i such that Pi<Qi, and Pj=Qj for all 1≤j<i.
1− ≤j
3l =
= Q
<
,1Input Q Format
15( <i
… ji
N
3f •The T first line of input will contain a single integer T, denoting the number of test cases.
,
∑
(A •Each test case consists of two lines of input.
jA •The A first line of each test case contains a single integer N — the length of the array A.
N
j
=
[] •The N1, second line contains N space-separated integers A1,A2,…,AN — the elements of array A.
A
ii A2,
N
Output
… …, Format
vj AN test case, output on a new line the value of i=1∑Nj=i∑Nval(f(A[i…j])),
9For each
a]
9modulo 998244353.
l)
8
()
2
f
4
(
4
A
3
[
5
i
3Input:
…
j
]
)
)
3
2
21
3
112
4
2102
output:
3
9
30