/
Time Limit: 2 sec / Memory Limit: 1024 MiB
配点 : 700 点
問題文
(1,2,\cdots,N) の順列 P=(P_1,P_2,\ldots,P_N) が与えられます。1\le L\le R\le N を満たす整数 L,R に対し、手順 f(L,R) を、以下の 2 ステップを順に行うものと定義します。
- P_L > P_R ならば、P_L, P_{L+1}, \cdots,P_R を反転する。つまり、P_R, P_{R-1},\cdots, P_L に置き換える。
- L<R ならば、f(L,R-1) を実行したのちに f(L+1,R) を実行する。
f(1,N) を実行した場合に反転が行われる回数を 998244353 で割った余りを求めてください。
制約
- 2 \le N \le 3 \times 10^5
- 1 \le P_i \le N
- P は (1,2,\cdots,N) の順列
- 入力される値はすべて整数
入力
入力は以下の形式で標準入力から与えられます。
N P_1 P_2 \ldots P_N
出力
答えを出力してください。
入力例 1
3 3 1 2
出力例 1
2
初め、P=(3,1,2) です。手順は以下の順に呼び出されます。
- f(1,3):P_1>P_3 なので反転し、P=(2,1,3) となります。
- f(1,2):P_1>P_2 なので反転し、P=(1,2,3) となります。
- f(1,1):P_1>P_1 が成り立たないため、反転は行われません。
- f(2,2):P_2>P_2 が成り立たないため、反転は行われません。
- f(2,3):P_2>P_3 が成り立たないため、反転は行われません。
- f(2,2):P_2>P_2 が成り立たないため、反転は行われません。
- f(3,3):P_3>P_3 が成り立たないため、反転は行われません。
- f(1,2):P_1>P_2 なので反転し、P=(1,2,3) となります。
反転は合計 2 回行われるため、答えは 2 です。
入力例 2
2 1 2
出力例 2
0
入力例 3
40 4 23 40 37 2 35 33 5 3 16 34 13 14 15 11 10 18 7 26 1 22 21 32 25 12 39 8 19 28 20 17 24 38 31 30 29 36 9 27 6
出力例 3
143250188
Score : 700 points
Problem Statement
You are given a permutation P=(P_1,P_2,\ldots,P_N) of (1,2,\cdots,N). For integers L,R satisfying 1\leq L\leq R\leq N, define the procedure f(L,R) as performing the following two steps in order.
- If P_L > P_R, reverse P_L, P_{L+1}, \cdots,P_R. That is, replace them with P_R, P_{R-1},\cdots, P_L.
- If L<R, execute f(L,R-1) and then execute f(L+1,R).
Find the number of reversals performed when f(1,N) is executed, modulo 998244353.
Constraints
- 2 \le N \le 3 \times 10^5
- 1 \le P_i \le N
- P is a permutation of (1,2,\cdots,N).
- All input values are integers.
Input
The input is given from Standard Input in the following format:
N P_1 P_2 \ldots P_N
Output
Output the answer.
Sample Input 1
3 3 1 2
Sample Output 1
2
Initially, P=(3,1,2). The procedures are called in the following order.
- f(1,3): Since P_1>P_3, a reversal is performed, resulting in P=(2,1,3).
- f(1,2): Since P_1>P_2, a reversal is performed, resulting in P=(1,2,3).
- f(1,1): Since P_1>P_1 does not hold, no reversal is performed.
- f(2,2): Since P_2>P_2 does not hold, no reversal is performed.
- f(2,3): Since P_2>P_3 does not hold, no reversal is performed.
- f(2,2): Since P_2>P_2 does not hold, no reversal is performed.
- f(3,3): Since P_3>P_3 does not hold, no reversal is performed.
- f(1,2): Since P_1>P_2, a reversal is performed, resulting in P=(1,2,3).
A total of 2 reversals are performed, so the answer is 2.
Sample Input 2
2 1 2
Sample Output 2
0
Sample Input 3
40 4 23 40 37 2 35 33 5 3 16 34 13 14 15 11 10 18 7 26 1 22 21 32 25 12 39 8 19 28 20 17 24 38 31 30 29 36 9 27 6
Sample Output 3
143250188