B. Reverse a Permutation

time limit per test

2 seconds

memory limit per test

256 megabytes

A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, 2,3,1,5,4 is a permutation, but 1,2,2 and 1,3,4 are not permutations.

You are given a permutation p of length n. You can perform the following operation exactly once:

  • Choose two integers l, r (1≤l≤r≤n).
  • Reverse the segment l,r in the permutation p.

Your task is to output the lexicographically maximum permutation that can be obtained by performing this operation. A permutation a is lexicographically greater than a permutation b if for the first position i where they differ, it holds that ai>bi.

Input

Each test consists of several test cases. The first line contains a single integer t (1≤t≤104) --- the number of test cases. The description of the test cases follows.

The first line of each test case contains the number n (1≤n≤2⋅105).

The second line of each test case contains n distinct integers p1,p2,...,pn (1≤pi≤n).

It is guaranteed that the sum of the values of n across all test cases does not exceed 2⋅105.

Output

For each test case, output the lexicographically maximum permutation that can be obtained with one operation.

Example

Input

Copy

复制代码

4

4

3 2 1 4

3

3 1 2

4

4 3 2 1

2

2 1

Output

Copy

复制代码

4 1 2 3

3 2 1

4 3 2 1

2 1

Note

For the first test case, the best segment is 1,4. After reversing, a=4,1,2,3. For the second test case, the best segment is 2,3. After reversing, a=3,2,1.

解题说明:此题是一道数学题,采用贪心算法。给定一个排列 a,判断能否通过一次区间反转将其变为降序排列 [n, n-1, ..., 1],并输出反转后的结果。采用贪心算法,从最大的值开始检查,找到第一个不在目标位置的值。

cpp 复制代码
#include<iostream>
#include<algorithm>
using namespace std;
int n, a[200001], b[200001];
int main()
{
	int ttt;
	cin >> ttt;
	while (ttt--)
	{
		cin >> n;
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
			b[a[i]] = i;
		}
		for (int i = n; i >= 1; i--)
		{
			if (b[i] == n - i + 1)
			{
				continue;
			}
			reverse(a + n - i + 1, a + b[i] + 1);
			break;
		}
		for (int i = 1; i <= n; i++)
		{
			cout << a[i] << " ";
		}
		cout << endl;
	}
}
相关推荐
Logic1011 小时前
C语言/数据结构排序题解:三个数的最大乘积——排序后比较两种候选情况
c语言·数据结构·数组·排序·时间复杂度·算法题·负数处理
无忧.芙桃1 小时前
位图妙用:512MB 实现 40 亿整数的存在性查询
c语言·c++·面试·哈希算法
听风若依2 小时前
数据在内存中的存储-纸面笔记整理
c语言·笔记
殷色玫瑰2 小时前
C++ string类详解:常用接口、字符串操作与模拟实现
java·linux·c语言·开发语言·数据结构·c++
Code_Solitude3 小时前
C语言:关于二维数组的作业总结
java·c语言·前端
老花眼猫4 小时前
数学艺术图案画-曼陀罗(93)
c语言·经验分享·青少年编程·课程设计
水饺编程5 小时前
第1章:下载 Linux 0.12 内核
linux·c语言·汇编·ubuntu
沐晓时光5 小时前
C语言入门,深入理解指针(2)
c语言·开发语言
Logic1015 小时前
C语言/数据结构贪心算法题解:字符串趋同——逐位统计最高频率求最小修改代价
c语言·数据结构·贪心算法·字符串·时间复杂度·频率统计·算法题