CF-Sort the Array

该博客主要讨论了一道编程题目,题目要求判断能否通过对数组中的一个区间进行反转来实现整个数组的升序排序。解题思路是找到第一个逆序对的开始位置和结束位置,然后反转该区间,再检查是否所有元素都满足升序。如果满足,则输出'yes'及反转区间,否则输出'no'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

Input

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).

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.

题意:

大意就是让你去选择a数组的一个区间中的l与r进行倒置,使得改变后的数组从小到大排序。

解题思路:

想法就是找到第一个违背a[i+1]>=a[i]的i作为l,接着往后遍历找到最后一个违背a[i]>=a[b]的i,作为e。

然后按照将【l,r】区间的数据进行倒置,接着遍历检查是否有违背a[i+1]>=a[i]的,有就输出“no”,否则输出“yes”。

 

#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#include<math.h>
using namespace std;
#define MAX 1000006
int a[MAX],b[MAX];
int ispr[MAX],pri[MAX];
int main()
{
    int n;
    cin>>n;
    for(int i=1; i<=n; i++)cin>>a[i];
    int b=1,f=0,e=1;
    for(int i=1; i<n; i++)
    {
        if(a[i+1]<a[i]&&!f)
        {

            b=i;
            f=1;
            e=i+1;
        }
        else if(a[b]>a[i]&&f)
        {
            e=i;

        }



    }
    if(a[n]<a[b])e=n;
    reverse(a+b,a+e+1);
    for(int i=1; i<n; i++)
    {
        if(a[i+1]<a[i])
        {
            cout<<"no";
            return 0;
        }


    }

    cout<<"yes\n"<<b<<" "<<e;

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值