#P8005. Reducible Permutations
Reducible Permutations
Reducible Permutations
Given two integers N and A, consider all permutations P = [P1, P2, ..., PN] of the set {1, 2, …, N} such that the first element is fixed to A (i.e. P1 = A). You are allowed to perform the following operation any number of times (possibly zero):
Select three positions x, y, z with x < y < z. If
\( P_y < \min\{P_x,P_z\} \quad \text{or} \quad P_y > \max\{P_x,P_z\} \),
then you may remove Py from the permutation.
A permutation is called reducible if there exists a sequence of such removals that results in a sequence of at most two numbers. Note that performing zero operations is allowed if the permutation already has at most two numbers.
Your task is to compute the number of reducible permutations (modulo \(998244353\)) among all permutations of length N with P1 = A.
Observation
It turns out that for any permutation of length at least 3, the only cases which are not reducible are the monotonic permutations (i.e. strictly increasing or strictly decreasing sequences), because in any triple taken from a monotonic sequence the middle element is the median and cannot be removed. Moreover, note that:
- For a strictly increasing permutation, the first element must be the smallest, so such a permutation exists only when \(A = 1\).
- For a strictly decreasing permutation, the first element must be the largest, so such a permutation exists only when \(A = N\).
Thus, when \(N \ge 3\), the total number of permutations with the given condition is \((N-1)!\). If \(A = 1\) or \(A = N\) then exactly one monotonic permutation exists (either strictly increasing or strictly decreasing, respectively) and is not reducible; otherwise all \((N-1)!\) permutations are reducible. Also note that when \(N \le 2\) the permutation already has at most two numbers and is trivially reducible.
The answer is therefore:
[ \text{answer} = \begin{cases} 1, & N \le 2, \ (N-1)! - \begin{cases}1, & \text{if } A=1 \text{ or } A=N, \ 0, & \text{otherwise,} \end{cases} & N \ge 3. \end{cases} ]
Output the answer modulo \(998244353\).
inputFormat
The input consists of a single line containing two integers N and A separated by a space.
Constraints:
- 1 ≤ N ≤ (constraint as per problem, e.g. 106)
- 1 ≤ A ≤ N
outputFormat
Output a single integer: the number of reducible permutations with P1 = A, modulo \(998244353\).
sample
1 1
1