B. Split Sort
B. Split Sort
You are given a permutation of integers to .
You can change the current permutation by applying the following operation several (possibly, zero) times:
- choose some ();
- create a new permutation by:
- first, writing down all elements of that are less than , without changing their order;
- second, writing down all elements of that are greater than or equal to , without changing their order;
- replace with the newly created permutation.
For example, if the permutation used to be and you choose , then you will first write down , then append this with . So the initial permutation will be replaced by .
Find the minimum number of operations you need to achieve for . We can show that it is always possible to do so.
A permutation of length is an array consisting of distinct integers from to in arbitrary order. For example, is a permutation, but is not a permutation ( appears twice in the array), and is also not a permutation ( but there is in the array).
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains one integer ().
The second line of each test case contains integers (). It is guaranteed that is a permutation.
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output the answer on a separate line.
Example
input
5 1 1 2 2 1 6 6 4 3 5 2 1 3 3 1 2 19 10 19 7 1 17 11 8 5 12 9 4 18 14 2 6 15 3 16 13
output
0 1 4 1 7
Note
In the first test case, and , so there is nothing left to do.
In the second test case, we can choose and we immediately obtain , .
In the third test case, we can achieve the minimum number of operations in the following way:
- : ;
- : ;
- : ;
- : .
解题思路
首先很明显可以从枚举到依次进行操作,那么至少次就可以将整个序列变成升序。因此很自然会想到某些是否没有必要进行操作。
当从枚举到并完成操作后,此时恰好有。接着对进行操作,而改变的地方只有将变成,让在的前面。如果在的前面,是否可以不进行的操作呢?可以发现如果跳过而对进行操作,那么就会得到。因此如果发现在的前面,那么我们就可以跳过的操作。而如果在的后面,那么必须要进行的操作,否则永远无法将变到的前面。
因此记录初始时数组中每个数的下标,然后从小到大枚举每个数,如果发现,说明可以跳过这个操作,否则进行。
AC代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef long long LL; 5 6 const int N = 1e5 + 10; 7 8 int p[N]; 9 10 void solve() { 11 int n; 12 scanf("%d", &n); 13 for (int i = 0; i < n; i++) { 14 int x; 15 scanf("%d", &x); 16 p[x] = i; 17 } 18 int ret = 0; 19 for (int i = 1; i < n; i++) { 20 if (p[i + 1] < p[i]) ret++; 21 } 22 printf("%d\n", ret); 23 } 24 25 int main() { 26 int t; 27 scanf("%d", &t); 28 while (t--) { 29 solve(); 30 } 31 32 return 0; 33 }
参考资料
Pinely Round 2 Editorial:https://codeforces.com/blog/entry/119902
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17669256.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2022-08-31 石子合并