Sort the Array
题目:Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.
Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a.
The second line contains n distinct space-separated integers: a[1], a[2], …, a[n] (1 ≤ a[i] ≤ 109).
Output
Print “yes” or “no” (without quotes), depending on the answer.
If your answer is “yes”, then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.
Examples
Input
3
3 2 1
Output
yes
1 3
Input
4
2 1 3 4
Output
yes
1 2
Input
4
3 1 2 4
Output
no
Input
2
1 2
Output
yes
1 1
Note
Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.
Sample 3. No segment can be reversed such that the array will be sorted.
Definitions
A segment [l, r] of array a is the sequence a[l], a[l + 1], …, a[r].
If you have an array a of size n and you reverse its segment [l, r], the array will become:
a[1], a[2], …, a[l - 2], a[l - 1], a[r], a[r - 1], …, a[l + 1], a[l], a[r + 1], a[r + 2], …, a[n - 1], a[n].
题目大意为:对一个数列,如果翻转一段数据后,能成为一个递增数列即输出yes,同时输出这段数据的起始位置和终点位置,否则输出no;
整体思路:分别定义两个数组,一个存放sort排序后的,一个存放原始数据;
然后进行比较这两个数组,找出不同的数据段的始末位置;然后对这段数据记行翻转比较,即用未排序最后的数据,与排序的起始数据比较,若一直相同,即可满足条件,否则不满足;
具体代码如下:
#include"iostream"
#include"algorithm"
using namespace std;
int a[100005],b[100005];//定义两个数组,存放原始数组与未排序的数组
int main()
{
int n;
while(scanf("%d",&n)==1)
{
int sum=0,c=0,d=0,e,f=0,g=0,h,flag=1;
for(int i=0;i<n;i++)
{cin>>a[i];b[i]=a[i];}
sort(a,a+n);//对a数组进行排序
for(int j=0;j<n;j++)
{
if(a[j]!=b[j]&&sum==0)//找到不同数据段的起始点;
{f=c=j;sum++;}//起点存两次;for循环会用到两次起点
else if(a[j]!=b[j])
{g=d=j;}//终点也存两次。for循环会用到两次;否则值会改变
}
for(c,d;c<=g;c++,d--)//直接从起始点开始循环比较
{
if(b[c]!=a[d]) flag=0;//设立标志,flag=0时,即不满足条件;
}
if(flag==1)
cout<<"yes"<<endl<<f+1<<" "<<g+1<<endl;//数组从零开始存贮,所以位置加一
if(flag==0) cout<<"no"<<endl;
}
return 0;
}