#P4678. Sum of Interval Similarity Counts

    ID: 17924 Type: Default 1000ms 256MiB

Sum of Interval Similarity Counts

Sum of Interval Similarity Counts

Consider two permutations P1 and P2 of the integers from 1 to n. For any sequence P of length m, define
\( C(P, x)=\#\{j\mid 1\le j\le m,\; P_j<x\} \).

We say that two sequences A and B of length m are similar if for every index i (1 ≤ i ≤ m),
\( C(A, A_i)=C(B, B_i) \). In other words, their relative order (or pattern) is identical.

For two permutations P1 and P2 of length n, define a function
\( F(P_1,P_2) \) to be the number of pairs (l, r) with 1 ≤ l ≤ r ≤ n such that:

  1. The subarrays P1[l..r] and P2[l..r] are similar (i.e. they have the same relative order).
  2. The subarray P1[l..r] has at most \( E \) inversions. (An inversion in a sequence S is a pair of indices i < j such that Si > Sj.)

Your task is to calculate the sum of \( F(P_1,P_2) \) over all pairs of permutations P1 and P2 of \( \{1,2,\dots,n\} \).

Explanation: For any fixed interval [l,r] of length \( k=r-l+1 \):

  • There are \( n-k+1 \) choices of placement (the number of intervals of length k in a permutation of length n).
  • For the subarray in P1, the number of ways to choose the k numbers and arrange them so that the number of inversions is at most \( E \) is f(k,E) multiplied by \( \binom{n}{k}\times (n-k)! \) (the latter factor is the number of ways to fill in the rest of the permutation). Note that \( \binom{n}{k}\times (n-k)!=\frac{n!}{k!} \).
  • For P2, to have the subarray similar to that of P1, its relative order must match exactly, and there is exactly 1 way to arrange any chosen set in that fixed pattern; its count over full permutations is also \( \frac{n!}{k!} \).
Thus, the final answer is given by: \[ \text{Answer} = \sum_{k=1}^{n} (n-k+1)\cdot f(k,E)\cdot\left(\frac{n!}{k!}\right)^2, \] where f(k,E) is the number of permutations of length k with at most \( E \) inversions.

inputFormat

The input consists of a line with two integers n and E.
n: the size of the permutation.
E: the maximum allowed inversions in the subarray of P1.

outputFormat

Output a single integer, the sum of \( F(P_1,P_2) \) over all pairs of permutations P1 and P2.

sample

3 1
147