B. Sort the Array
time limit per test
memory limit per test
input
output
a consisting of n distinct
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
n (1 ≤ n ≤ 105) — the size of array a.
n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109).
Output
yes" or "no" (without quotes), depending on the answer.
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.
Sample test(s)
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
大体题意:
给你一个数组,问是否可以逆序一个子数组,使得整体呈递增序列!
写这个博客,主要记录一下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;
}