luogu#P8180. 「EZEC-11」Unmemorable

「EZEC-11」Unmemorable

Problem Description

Unputdownable has a permutation aa of length nn.

While practicing monotonic stacks, he used a program to compute, for each ii, the largest lil_i such that ali<aia_{l_i} < a_i and li<il_i < i, and the smallest rir_i such that ari<aia_{r_i} < a_i and ri>ir_i > i.

In particular, if such an lil_i does not exist, it is defined as 00, and if such an rir_i does not exist, it is defined as n+1n+1.

One day, Unputdownable forgot the permutation aa, and only the arrays ll and rr after being rearranged separately were left. Can you help him recover the original permutation aa?

Later, since he found that aa cannot be recovered, you only need to tell him how many possible original permutations aa there are.

Output the answer modulo 998244353998244353. The testdata guarantees that at least one solution exists.

Input Format

The first line contains an integer nn.

The second line contains nn integers, representing the rearranged ll.

The third line contains nn integers, representing the rearranged rr.

Output Format

Output one line containing one integer, the number of possible permutations modulo 998244353998244353.

5
3 1 0 0 4
6 3 6 3 6

6

Hint

Sample Explanation 1

One possible permutation is {2,5,1,3,4}\{2,5,1,3,4\}. The ll array is {0,1,0,3,4}\{0,1,0,3,4\}, and the rr array is {3,3,6,6,6}\{3,3,6,6,6\}.

This problem uses bundled tests.

  • Subtask 1 (5 pts): n8n \leq 8.
  • Subtask 2 (15 pts): rinr_i \geq n.
  • Subtask 3 (15 pts): n2000n \leq 2000, and it is guaranteed that there exists a permutation aa such that the l,rl, r computed from aa are exactly the given ones.
  • Subtask 4 (25 pts): n106n \leq 10^6, and it is guaranteed that there exists a permutation aa such that the l,rl, r computed from aa are exactly the given ones.
  • Subtask 5 (40 pts): No special constraints.

For 100%100\% of the testdata, 1n1061 \leq n \leq 10^6, 0li,rin+10 \leq l_i, r_i \leq n+1. The testdata guarantees that at least one solution exists.

Translated by ChatGPT 5