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;
	}
}
相关推荐
烟烟Abandon7 小时前
FFmpeg开发基础之 C 语言中的指针(下篇)
c语言·ffmpeg
Navigator_Z7 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
草莓熊Lotso1 天前
Qt 进阶控件实战:下拉框、列表、表格 + 旋钮 / 滑动条全攻略
大数据·c语言·开发语言·c++·人工智能·qt
龙砚序1 天前
【数据结构|线性表实战 01】基于顺序表的地铁站点管理:查找、增删、有序二路归并(C 语言实现)
c语言·数据结构·算法
龙砚序1 天前
【数据结构|栈实战 03-1】顺序栈完整实现与工程应用:浏览器历史回溯、IP 地址进制转换(C 语言)
c语言·数据结构·tcp/ip
wuminyu1 天前
OpenJDK学习笔记:如何构建支持动态注册、注销和重新注册的 Native回调管理器
java·linux·c语言·jvm·c++
金榜题名萱1 天前
蓝桥杯 - 拍照 —— 动态规划
c语言·数据结构·c++·算法·职场和发展·蓝桥杯·动态规划
Matt Feng2 天前
STM32串口ISP多路烧录:4个关键参数与批量下载步骤
c语言·stm32·单片机·嵌入式硬件·接口隔离原则
derek19972 天前
软考软件设计师:B-树和 B+树的区别、线性探查法查找时到底比较了谁
c语言·c++·计算机网络·软件工程·学习方法
小灰灰搞电子2 天前
C 语言基础:动态内存管理详解
c语言·开发语言