PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: am_aadvik
Tester: iceknight1093
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
Fenwick trees/segment trees
PROBLEM:
You’re given a permutation P, and a parameter K.
You can do the following:
- Choose a subarray of length at most K, and move the maximum element in this subarray to the leftmost position of the subarray.
Find the minimum number of moves needed to sort P in descending order, if it’s possible at all.
EXPLANATION:
If K = 1, then we functionally cannot move any element at all.
So, if P is already in the desired order the answer is 0, otherwise the answer is -1.
For K \ge 2, we can always swap adjacent elements (when the smaller one is to the left), and so we can always reach [N, N-1, \ldots, 1]. The question now is purely to find the minimum number of moves needed.
For K = 2, we can really only swap adjacent elements - and only with P_i \lt P_{i+1}.
In particular, for each pair of indices (i, j) such that i \lt j and P_i \lt P_j, the element P_j will need to end up to the left of element P_i and so this pair will have to swap at some point.
The answer (when K = 2) is thus the number of pairs with i \lt j and P_i \lt P_j.
For K \gt 2 we can generalize this idea a bit.
Consider the element P_i.
Suppose there are x_i elements to its left that are smaller than it.
P_i needs to end up moving across all these x elements.
However, a single move allows P_i to move at most K-1 steps (by choosing a subarray of length K.)
So, the number of moves needed for P_i to cross everything smaller than it is bounded below by
A lower bound on the answer is hence obtained by summing up this across all i, i.e.
It’s easy to see that this bound is attainable, if we put elements into place from largest to smallest - that is, move N to position 1 as quickly as possible, then move N-1 to position 2, and so on.
Thus only the x_i values need to be found quickly - the remainder is easy.
One way to find the x_i values is to use a data structure such as a segment tree or a fenwick tree, that supports point updates and range sum queries.
With such a data structure, we can do the following:
- Consider a new array A of length N, where initially A_i = 0 for all i.
- We’ll process elements (not indices) in the order 1, 2, \ldots, N.
When processing element y, the array A will mean the following:- If P_i \lt y, then A_i = 1 will hold.
- If P_i \ge y, then A_i = 0 will hold.
- Assuming this is the case, then if element y appears at index i we can simply set x_i = A_1 + \ldots + A_{i-1}.
- After doing this, we update A_i itself to contain the value 1, i.e. “activate” y for larger values.
This allows us to compute all x_i in \mathcal{O}(N\log N) time which is fast enough.
TIME COMPLEXITY:
\mathcal{O}(N\log N) per testcase.
CODE:
Editorialist's code (PyPy3)
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/FenwickTree.py
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i | (i + 1)
if j < len(x):
x[j] += x[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
while idx < len(self.bit):
self.bit[idx] += x
idx |= idx + 1
def query(self, end):
"""calc sum(bit[:end])"""
x = 0
while end:
x += self.bit[end - 1]
end &= end - 1
return x
def findkth(self, k):
"""Find largest idx such that sum(bit[:idx]) <= k"""
idx = -1
for d in reversed(range(len(self.bit).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(self.bit) and k >= self.bit[right_idx]:
idx = right_idx
k -= self.bit[idx]
return idx + 1
for _ in range(int(input())):
n, k = map(int, input().split())
p = list(map(int, input().split()))
if k == 1:
if p == sorted(p, reverse=True): print(0)
else: print(-1)
continue
pos = [0]*(n+1)
for i in range(n):
pos[p[i]] = i
f = FenwickTree([0]*n)
ans = 0
for i in range(1, n+1):
ans += (f.query(pos[i]) + k - 2) // (k-1)
f.update(pos[i], 1)
print(ans)