PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000107. Dãy con Kadomatsu đẹp (Beautiful Kadomatsu)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Dãy con Kadomatsu đẹp (Beautiful Kadomatsu)

Beautiful Kadomatsu

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation P=(P1,P2,…,Pn)P=(P_1,P_2,\ldots,P_n) of the integers from 11 through nn. You may choose any increasing sequence of indices, not necessarily consecutive, to form a subsequence b=(b1,b2,…,bk)b=(b_1,b_2,\ldots,b_k).

A position ii with 2≤i≤k−12\le i\le k-1 is a peak if bi−1<bi>bi+1b_{i-1}<b_i>b_{i+1}. A position in the same range is a valley if bi−1>bi<bi+1b_{i-1}>b_i<b_{i+1}.

Let xx be the number of peaks and yy the number of valleys. The subsequence is called kadomatsu-like if and only if x>yx>y. A subsequence of length one or two has no internal position and cannot satisfy this condition.

Count all kadomatsu-like subsequences of PP. Different index selections count separately, even though the chosen positions need not be consecutive. Print the count modulo 998244353998244353.

Input

  • The first line contains the integer nn, the permutation length.
  • The second line contains exactly nn integers P1,P2,…,PnP_1,P_2,\ldots,P_n in permutation order.

Output

Print the number of kadomatsu-like subsequences, modulo 998244353998244353.

Subtasks

  • Subtask 1 (20 points): 1≤n≤121\le n\le 12; PP is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; PP is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).
  • Subtask 3 (50 points): 1≤n≤3000001\le n\le 300000; PP is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).

Examples

Example 1

Input

4
1 3 4 2

Output

4

Explanation

The qualifying subsequences are (1,3,4,2)(1,3,4,2), (1,3,2)(1,3,2), (1,4,2)(1,4,2), and (3,4,2)(3,4,2). Each length-three sequence has one peak and no valley. The length-four sequence has a single peak at 44 and no valley. Every other subsequence has no excess of peaks. Thus the answer is 4.

Example 2

Input

1
1

Output

0

Explanation

The only non-empty subsequence is (1)(1), of length one. It has no internal positions, so x=y=0x=y=0; therefore x>yx>y is false and the answer is 0.

Example 3

Input

20
11 10 18 13 12 16 5 19 7 6 17 4 9 1 14 2 20 15 8 3

Output

431610

Explanation

For instance, (10,13,12,5,7,9,20,3)(10,13,12,5,7,9,20,3) has two peaks (13,2013,20) and one valley (55), hence it qualifies. Counting all selections by extending subsequences that start with an ascent and end with a descent, the cumulative qualifying counts after positions 5,10,15,205,10,15,20 are 8,384,7227,4316108,384,7227,431610, respectively. The final answer is 431610 (less than the modulus).