Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array aa consisting of nn distinct integers.
Unfortunately, the size of aa 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 aa (in increasing order) by reversing exactly one segment of aa ? See definitions of segment and reversing in the notes.
input
The first line of the input contains an integer nn ( 1<=n<=10^{5}1<=n<=10
5
) — the size of array aa .
The second line contains nn distinct space-separated integers: a[1],a[2],…,a[n]a[1],a[2],…,a[n] ( 1<=a[i]<=10^{9}1<=a[i]<=10
9
).
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.
题目意思:给你一个序列,让你判断是否能够只通过一次翻转序列中的某一部分使之成为一个上升序列。并且翻转的那一部分是连续的。
题解:找出已知序列中一段完整的降序序列,将此段序列翻转成为上升序列,再判断翻转过后的序列是不是为上升序列,如是,则输出yes和翻转序列的区间,否则输出no。
*注意:*此处寻找下标是巧用了for循环的,具体代码中见!
#include<iostream>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int a[100005];
int main(){
int n,l=1,r=1;
cin>>n;
for(int i=1; i<=n; i++)scanf("%d",&a[i]);
for(int i=1; i<n; i++){
if(a[i]>a[i+1]){
l=i;
break;
}
}
for(int i=n; i>1; i--){
if(a[i]<a[i-1]){
r=i;
break;
}
}
// cout<<l<<' '<<r<<endl;
reverse(a+l,a+r+1);
bool f=false;
//此处查找的范围应该是整个数组,排除3,1,2,4 这种情况!
for(int i=1; i<n; i++){
// cout<<a[i]<<' ';
if(a[i]>a[i+1]){
f=true;
break;
}
}
if(f)cout<<"no"<<endl;
else cout<<"yes"<<endl<<l<<' '<<r<<endl;
return 0;
}