Codeforces Round 1011 (Div. 2)
F2
Serval and Colorful Array (Hard Version)
Codeforces
2900
原题
← F1→
翻译中…

This is the hard version of the problem. The difference between the versions is that in this version, $n\le 4\cdot 10^5$. You can hack only if you solved all versions of this problem.

翻译中…

Serval has a magic number $k$ ($k\ge 2$). We call an array $r$ colorful if and only if:

翻译中…
  • The length of $r$ is $k$, and
  • Each integer between $1$ and $k$ appears exactly once in $r$.
翻译中…

You are given an array $a$ consisting of $n$ integers between $1$ and $k$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once. You can perform the following operation on $a$:

翻译中…
  • Choose an index $i$ ($1\le i \lt n$), then swap $a_i$ and $a_{i+1}$.
翻译中…

Find the minimum number of operations needed to make at least one subarray$^{\text{∗}}$ of $a$ colorful. It can be shown that this is always possible under the constraints of the problem.

翻译中…

$^{\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). The description of the test cases follows.

翻译中…

The first line of each test case contains two integers $n$ and $k$ ($2\leq k\leq n\leq 4\cdot 10^5$) — the length of the array $a$ and Serval's magic number.

翻译中…

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1\leq a_i\leq k$) — the elements of the array $a$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once.

翻译中…

It is guaranteed that the sum of $n$ over all test cases does not exceed $4\cdot 10^5$.

翻译中…

Output

翻译中…

For each test case, output a single integer — the minimum number of operations needed to make at least one subarray of $a$ colorful.

翻译中…

Note

翻译中…

In the first test case, since the subarrays $[a_1, a_2] = [1, 2]$ and $[a_2, a_3] = [2, 1]$ are already colorful, we do not need to perform any operations. Thus, the answer is $0$.

翻译中…

In the second test case, we can swap $a_1$ and $a_2$ to obtain $[1, \underline{2, 1, 3}, 1, 1, 2]$, which has a colorful subarray $[a_2, a_3, a_4] = [2, 1, 3]$. And the given array initially does not have any colorful subarrays, so the answer is $1$.

翻译中…

样例

Input #1
6
3 2
1 2 1
7 3
2 1 1 3 1 1 2
6 3
1 1 2 2 2 3
6 3
1 2 2 2 2 3
10 5
5 1 3 1 1 2 2 4 1 3
9 4
1 2 3 3 3 3 3 2 4
Output #1
0
1
2
3
4
5
InputCopy OutputCopy
题目信息
题号
2085F2
时间限制
2 s
内存限制
512 MB
标签
数据结构
贪心

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。