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.
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).
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.
3 3 2 1
yes 1 3
4 2 1 3 4
yes 1 2
4 3 1 2 4
no
2 1 2
yes 1 1
大体题意:
给你一个数组,问是否可以逆序一个子数组,使得整体呈递增序列!
写这个博客,主要记录一下reverse可以倒序!
思路:
从左到右找到第一个左边大于右边的
从右到左找到第一个小于左边的!
逆序!
检测是否是递增序列!
如果没有找到,就是两个记录变量都没被赋值,那么就是yes 输出1 1
否则检测。。。
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn];
int main()
{
int n;
while(cin >> n){
int s=-1,e=-1;
for (int i = 0; i < n; ++i)cin >> a[i];
for (int i = 0; i < n-1; ++i)if (a[i] > a[i+1]){s=i;break;}
for (int i = n-1; i >= 1; --i)if (a[i]<a[i-1]){e=i;break;}
if (s==-1 || e == -1)printf("yes\n1 1\n");
else {
reverse(a+s,a+e+1);
bool ok = false;
for (int i = 0; i < n-1; ++i){
if (a[i] > a[i+1]){ok=true;break;}
}
if (ok)printf("no\n");
else printf("yes\n%d %d\n",s+1,e+1);
}
}
return 0;
}