Блог пользователя memset0

Автор memset0, история, 8 лет назад, По-английски

codeforces is full of intelligent people... :D

Can anyone please explain the process , how to solve this problem ???

I read the editorial but that was unclear to me :(

  • Проголосовать: нравится
  • -11
  • Проголосовать: не нравится

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

Very nice problem. I'll explain my solution.

  • First part: When we swap adjacent elements, we are either creating a new inversion or removing one. If we make K adjacent swaps, we'll end up with at most K inversions and the total number of inversions will have the same parity as K. To calculate this, we can use bottom-up DP. Let Ai, j be the amount of arrays of length i with j inversions. Suppose we are at state i, j and we want to add element i + 1 to the current array. We have i + 1 positions to choose from, and each position will create one inversion more than the position to its right. If we push it to the back of the array, we won't create any new inversion, and if we push it to the front of the array, we'll be creating i new inversions. So we will need to add Ai, j to all elements Ai, k with k in the range [j, j + i]. This process is O(n3) if done naively, so if we want it to run in time, we will need to use a BIT to do range additions.
  • Second part: A permutation can be seen as a collection of cycles. The identity permutation (1,2,3,4,...,N) has N cycles. When we swap two elements, if they belong to the same cycle, we'll be dividing this cycle into two cycles, and if they belong to different cycles, we'll be merging them. So, we are either creating a new cycle or removing one cycle by merging two different cycles. If we make at most K swaps in total, we will have at least N - K cycles in the end. To calculate this, we can use bottom-up DP too. Let Bi, j be the amount of permutations of length i with j cycles. Suppose we are at state i, j and we want to add element i + 1. We have two choices here, the first one being to point it to itself, creating a new cycle, and the second choice to point it to some previous element (making that previous element point to the new one in the process), effectively extending one existing cycle's length by 1. We have i positions for the second choice, so we have to add Bi, j to Bi + 1, j + 1 and Bi, j * i to Bi + 1, j. This process is O(N2), so we don't need any special data structure.
C++ Code