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;
	}
}
相关推荐
another heaven13 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude13 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
Zwawa16 小时前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式
꧁细听勿语情꧂18 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
§ꦿCFོ༉1 天前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习
Severus_black2 天前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
唐青枫2 天前
C 语言 strcpy() 用法详解与实战 Demo
c语言
程序猿打工仔2 天前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法
꧁细听勿语情꧂2 天前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法
是main不是漫2 天前
【C++——类和对象(上)】筑基篇:以封装奠定面向对象之基
c语言·开发语言·c++