#P9662. [ICPC2021 Macao R] Cyclic Buffer

[ICPC2021 Macao R] Cyclic Buffer

题目描述

There is a cyclic buffer of size nn with readers from the 11-st position to the kk-th position (both inclusive). Let aia_i (1in1 \le i \le n) be the integer at the ii-th position of the buffer initially. What's more, a1,a2,,ana_1, a_2, \cdots, a_n form a permutation of nn.

We're going to visit all the integers from 11 to nn (both inclusive) in increasing order. An integer can be visited only when it is residing in positions with readers (that is to say, when it is in the first kk positions). In case that an integer cannot be visited, we can shift the whole buffer in either directions any number of times.

  • If we shift the buffer to the left once, integers in the ii-th position will be moved to the (i1)(i - 1)-th position if i>1i > 1, and integer in the 11-st position will be moved to the nn-th position.
  • If we shift the buffer to the right once, integers in the ii-th position will be moved to the (i+1)(i + 1)-th position if i<ni < n, and integer in the nn-th position will be moved to the 11-st position.

What's the minimum number of times to shift the buffer so that we can visit all the integers in increasing order?

输入格式

There are multiple test cases. The first line of the input contains an integer TT indicating the number of test cases. For each test case:

The first line contains two integers nn and kk (1kn1061 \le k \le n \le 10^6) indicating the size of the buffer and the number of readers.

The second line contains nn integers a1,a2,,ana_1, a_2, \cdots, a_n (1ain1 \le a_i \le n) where aia_i indicates the integer in the ii-th position of the buffer initially.

It's guaranteed that the given nn integers form a permutation of nn. It's also guaranteed that the sum of nn of all test cases will not exceed 10610^6.

输出格式

For each test case output one line containing one integer indicating the minimum number of times to shift the buffer so that all integers can be visited in increasing order.

2
5 3
2 4 3 5 1
1 1
1
3
0

提示

For the first sample test case:

  • Shift to the right once so the buffer becomes {1,2,4,3,5}\{1, 2, 4, 3, 5\}. 11 and 22 can now be visited in order as they are in the first 33 positions.
  • Shift to the left twice so the buffer becomes {4,3,5,1,2}\{4, 3, 5, 1, 2\}. 33, 44 and 55 can now be visited in order as they are in the first 33 positions.