As a huge fan of the popular collectible card game Numinous Wilds: the Elven Reign Chronicles (NWERC), you have a large collection of cards which you carefully organise by their rarity. One day you notice that someone has touched your collection, and that some of the cards are now out of order. The most natural suspect, of course, is your little brother Billy, who was absolutely 100% forbidden from playing with your cards. After a few minutes of interrogation Billy confesses that he indeed took a few consecutive cards from the middle of the stack, but he swears that he put them back in exactly the same order as they were. You suspect that Billy, being so young, may have simply mistakenly reversed the order of the cards that he took. Now you want to check your theory and decide if you can find the batch of cards that Billy took to play with.
Is it possible to restore the order of the cards in to non-decreasing order of their rarity by reversing just one contiguous batch of cards?
The input consists of:
• One line containing an integer n (1 ≤ n ≤ 10^6), the number of cards in your collection.
• One line containing n integers v1,...,vn (1 ≤ vi ≤ 10^9 for all i), the current order of the cards’ rarity values.
If the cards can be sorted by reversing exactly one contiguous subsequence of the list, then output the 1-based start and end indices of such a subsequence. Otherwise, output “impossible”. If there are multiple valid solutions you may output any one of them.
本题答案不唯一,符合要求的答案均正确
样例输入1复制
7 10 13 19 19 15 14 20
样例输出1复制
3 6
样例输入2复制
6 9 1 8 2 7 3
样例输出2复制
impossible
样例输入3复制
3 1 2 3
样例输出3复制
2 2
题意:给你一串数字,要求你找到一串子序列,把这串子序列直接颠倒过来,可以将整串数字变成从小到大排列的序列。
思路:对于原序列a1,a2,...,an,构建一个与之完全相同的序列b1,b2,...,bn.并将b从小到大排序。
将序列a与序列b依次比较,left为从前往后比较第一个a[i]与b[i]不同的i,right为从后往前比较第一个a[i]与b[i]不同的i。
如果left,right都为0,说明原序列原本就是从小到大排列,输出"1 1".
如果left,right不为0,查找从下标left到right-1有没有a[i]<a[i+1]的数出现,如果出现说明不可能只颠倒一个子序列就可以将整个序列变成从小到大排列的序列 。如果没有这样的数出现,输出left,right。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
const int N=1e6+10;
typedef long long ll;
int a[N];
int b[N];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(b+1,b+n+1);
bool flag=0;
int left=0,right=0;
for(int i=1;i<=n;i++)
if(a[i]!=b[i])
{
left=i;
break;
}
for(int i=n;i>=1;i--)
if(a[i]!=b[i])
{
right=i;
break;
}
for(int i=left;i<=right-1;i++) if(a[i]<a[i+1]) flag=1;
if(!left&&!right) printf("1 1\n");
else if(left&&right&&!flag) printf("%d %d\n",left,right);
else if(left&&right&&flag) printf("impossible\n");
return 0;
}