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;
	}
}
相关推荐
Navigator_Z6 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
爱读书的小胖9 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节
Pointer Pursuit10 小时前
Linux环境变量
linux·服务器·c语言·链表·1024程序员节
CHHH_HHH10 小时前
【Linux网络篇】初识网络与Socket编程基础
linux·服务器·c语言·开发语言·网络·后端·1024程序员节
思麟呀10 小时前
BTree的原理与 C++ 完整实现
c语言·数据结构·c++·算法·1024程序员节
qq_4086068611 小时前
C_Primer_Plus_chapter17_exercise3
c语言·1024程序员节
H.莓飛12 小时前
【数据结构】排序_OJ题(二):划分与选择
linux·服务器·c语言·开发语言·数据结构·visual studio
思麟呀13 小时前
嵌入式入门(四)USART 串口深度解析:单片机第一次与电脑对话
c语言·单片机·嵌入式硬件·1024程序员节
wuminyu13 小时前
JVM规范学习总结-Java源码经过javac编译后产物
java·linux·c语言·jvm·c++
小白今天也很酷13 小时前
MCXN947更新板载DAP_Link固件的方法
c语言·python·单片机·ubuntu·excel·1024程序员节