sort the array

洛谷题目链接

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值