题目
ChenJr给你一个长度为n的排列p,你可以交换其中任意相邻的两个数。现在你需要用最小的交换次数使得这个排列变成升序的序列。现在ChenJr想知道,对于这个排列p,是否存在唯一的交换方式,使得这个排列变成升序的序列。
Input
第一行包含一个正整数T (1≤T≤5∗104),代表有T组样例。
对于每组样例,第一行包含一个n (1≤∑n≤105),代表排列的大小。
下一行包含n个正整数pi,代表排列的值。
Output
对于每组样例,输出一行’Y’或者’N’。
如果交换方式唯一,则输出’Y’,否则输出’N’。
Example
inputCopy
3
1
1
3
3 2 1
4
3 1 2 4
outputCopy
Y
N
Y
这个题意很清楚,我就不多说,就是问决策唯一性。
我们来看一下:当且仅当两个相邻数左大右小才可以交换。把这样的两个数称为可操作的数对。
这样的话,我们就可以想如果初始序列有大于一个这样的可操作的数对那么答案就是N,因为第一步就可以有多个操作。
换句话说:需要始终只有一个或者0个这样的可操作数对,保持到0,才算是Y,否则都是N。
那么假如有这样的数:…ai , aj , ak , al…;
这个序列只有aj , ak是可操作的数对,那操作之后我们不需要再用O(n)做法去扫整个序列就可以直接去判定,ai , ak, aj, al这3个相邻的对子有几个可操作的数对就行了。
于是完整代码已经很简单了:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <queue>
#include <stack>
#include <map>
//鬼畜头文件
using namespace std;
const int INF = 0x3f3f3f3f;
//1.06e9大小
const int mod = 1e9+7;
typedef unsigned long long ULL;
typedef long long LL;
//鬼畜define
int t;
int n;
int all[100010];
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int num=0;
int location;
for(int time=0;time<n;time++)
{
scanf("%d",&all[time]);
}
for(int time=0;time<n-1;time++)
{
if(all[time]>all[time+1])
{
++num;
location=time;
}
}
if(num>1)printf("N\n");
else if(num==0)printf("Y\n");
else
{
while(1)
{
if(location==n-2){printf("Y\n");break;}
int temp=all[location];
all[location]=all[location+1];
all[location+1]=temp;
if(all[location-1]>all[location]&&all[location+1]>all[location+2]){printf("N\n");break;}
else if(all[location-1]<=all[location]&&all[location+1]<=all[location+2]){printf("Y\n");break;}
else
{
if(all[location-1]>all[location])--location;
else ++location;
}
}
}
}
return 0;
}