「CF451B」 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.
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.
1 2 |
3 3 2 1 |
1 2 |
yes 1 3 |
1 2 |
4 2 1 3 4 |
1 2 |
yes 1 2 |
1 2 |
4 3 1 2 4 |
1 |
no |
1 2 |
2 1 2 |
1 2 |
yes 1 1 |
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].
题解
一个序列,问是否能翻转其中的一部分使得它成为上升序列
离散化完随便搞。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define ll long long #define inf 1000000000 using namespace std; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int n,m,l=1,r=1; int a[100005],b[100005],disc[100005]; int find(int x) { int l=1,r=n; while(l<=r) { int mid=(l+r)>>1; if(disc[mid]==x)return mid; else if(disc[mid]<x)l=mid+1; else r=mid-1; } } int main() { n=read(); for(int i=1;i<=n;i++) a[i]=disc[i]=read(); sort(disc+1,disc+n+1); for(int i=1;i<=n;i++) a[i]=b[i]=find(a[i]); for(int i=1;i<=n;i++) if(a[i]!=i) { l=i;r=a[i]; break; } for(int i=1;i<=r-l+1;i++) b[l+i-1]=a[r-i+1]; for(int i=1;i<=n;i++) if(b[i]!=i) { puts("no");return 0; } puts("yes"); printf("%d %d",l,r); return 0; } |