Sort the Array
Posted X_1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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
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].
直接暴力找。
#include<stdio.h> #include<algorithm> #include<iostream> using namespace std; int main() { int n; int a[100050]; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); int l=0,r=0; for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { l=i; r=l+1; break; } } if(r!=0) { for(int i=l;i<n-1;i++) { if(a[i]<a[i+1]) { r=i; break; } r=i+1; } } for(int i=0;i<(r-l)/2+1;i++) { int t=a[i+l]; a[i+l]=a[r-i]; a[r-i]=t; } int flag=1; for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { flag=0; break; } } if(flag) { printf("yes\n"); printf("%d %d",l+1,r+1); } else printf("no"); return 0; }
以上是关于Sort the Array的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 258B Sort the Array
js代码片段: utils/lcoalStorage/cookie
环境初始化 Build and Install the Apache Thrift IDL Compiler Install the Platform Development Tools(代码片段