0w1

Yuki 616 へんなソート

Problem Description:
You are given an array A with length N.
You have a weird "sorting" algorithm, the output is non-deterministic, but we know that it must be some arrangement of the input array, and contains no more than K inversions. Find the number of distinct possible permutations of the output.

Constraints:
1 ≤ N ≤ 300
0 ≤ K ≤ N * (N - 1) / 2
1 ≤ A[i] ≤ 1e9
All A[i] are distinct

Solution:
dp[i][j]: Having the smallest i values determined, with j inversions, number of ways
dp[1][0] = 1
dp[i][j] = sum(dp[i - 1][k] for k in (j - i)..j)
Workout the transition with partial sum maintained => O(1) transition cost => total TC: O(NK).

Code:

#include <bits/stdc++.h>

const int MOD = 1e9 + 7;

signed main() {
  std::ios::sync_with_stdio(false);
  int N, K;
  std::cin >> N >> K;
  std::vector<int> A(N);
  for (int i = 0; i < N; ++i) {
    std::cin >> A[i];
  }
  std::vector<std::vector<int>> dp(2, std::vector<int>(K + 1));
  std::vector<std::vector<int>> pdp(2, std::vector<int>(K + 1));
  dp[1][0] = 1;
  std::partial_sum(dp[1].begin(), dp[1].end(), pdp[1].begin());
  for (int i = 2; i <= N; ++i) {
    for (int j = 0; j <= K; ++j) {
      dp[i & 1][j] = pdp[~i & 1][j];
      if (j - (i - 1) - 1 >= 0) (dp[i & 1][j] -= pdp[~i & 1][j - (i - 1) - 1]) %= MOD;
      pdp[i & 1][j] = dp[i & 1][j];
      if (j) (pdp[i & 1][j] += pdp[i & 1][j - 1]) %= MOD;
    }
  }
  std::cout << ((pdp[N & 1][K] + MOD) % MOD) << std::endl;
  return 0;
}