Min Max Sort
题目描述:
You are given a permutation
You can perform the following operation any number of times (possibly zero):
- choose two different elements
and and erase them from the permutation; - insert the minimum of
and into the permutation in such a way that it becomes the first element; - insert the maximum of
and into the permutation in such a way that it becomes the last element.
For example, if
, then after the first step of the operation, the permutation becomes
Your task is to calculate the minimum number of operations described above to sort the permutation
输入描述:
The first line contains a single integer
The first line of the test case contains a single integer
The second line of the test case contains
The sum of
输出描述:
For each test case, output a single integer — the minimum number of operations described above to sort the array
样例:
input:
4
5
1 5 4 2 3
3
1 2 3
4
2 1 4 3
6
5 2 4 1 6 3
output:
2
0
1
3
Note:
In the first example, you can proceed as follows:
- in the permutation
, let's choose the elements and , then, after applying the operation, the permutation becomes ; - in the permutation
, let's choose the elements and , then, after applying operation, the permutation becomes .
AC代码:
#include <bits/stdc++.h> using namespace std; // 对于n个数,可以从1 ~ n, 2 ~ n - 1, 3 ~ n - 2...这样子操作 // 如果原数组中两个数的位置跟排列中的不一样就说明两个数需要操作 // 如果两个数需要操作,那么由于操作会把两个数放在最左边和最右边 // 所以在排列中这两个数左右两边的所有数也需要操作 // 所以可以从排列中间的数开始,判断原数组两个数的相对位置 // 依次往两边判断两个数是否需要操作 // 最后l和r所指的那两个数就是最先需要操作的那两个数,输出l即可 void solve() { int n; scanf("%d", &n); vector<int> pos(n + 1); // 存每个数的位置 for(int i = 1; i <= n; i ++) { int x; scanf("%d", &x); pos[x] = i; // x 的位置在 i } // 不用考虑奇偶的情况 int l = (n + 1) / 2, r = (n + 2) / 2; while(l > 0 && (l == r || (pos[l] < pos[l + 1] && pos[r - 1] < pos[r]))) { l --; r ++; } printf("%d\n", l); } int main() { int T; scanf("%d", &T); while(T --) solve(); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】