451B - Sort the Array

链接:

https://codeforces.com/problemset/problem/451/B

题意:

给一个长度n的数组,翻转一个下标l到r的数列使数列递增

输出是否能完成,能完成的话翻转什么位置

输入

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

解:

遍历出递减数列的位置和个数,记录第一个递减数列的位置

如果有一个以上递减数列,翻转一次不能使数列递增

默认设置位置l=1,r=1,这样一个递减数列时直接翻转

没有递减数列时让1,1翻转(等于不变)

然后比较交换后的数列和排序后的数列,一样即可

实际代码:

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1E5+5;
int sz[N];
int st[N];
int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>sz[i]; 
		st[i]=sz[i];
	}
	sort(st+1,st+n+1);
	bool nc=0;
	int ans=0;
	int l=1,r=1;
	for(int i=1;i<n;i++)
	{
		if(sz[i]>sz[i+1])
		{
			if(nc==0)
			{
				if(ans==0)
				{
					l=i;
				}
				nc=1;
				ans++;
			}
		}
		else
		{
			if(ans==1&&nc==1)
			{
				r=i;
			}
			if(nc==1)nc=0;
		}
		if(ans==1&&i==n-1&&sz[n-1]>sz[n])
		{
			r=n;
		}
	}
	//cout<<ans<<endl;
	if(ans>1) cout<<"no"<<endl;
	else
	{
		bool sc=1;
		//cout<<l<<r<<endl;
		reverse(sz+l,sz+r+1);
		for(int i=1;i<=n;i++)
		{
			//cout<<sz[i]<<" "<<st[i]<<endl;
			if(sz[i]!=st[i])
			{
				sc=0;
				break;
			}
		}
		if(sc)
		{
			cout<<"yes"<<endl;
			cout<<l<<" "<<r<<endl;
		}
		else cout<<"no"<<endl;
	}

}

限制:

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值