【CodeForces】451B 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.

解题思路

代码

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 bool a[500000];
 7 int temp[500000];
 8 inline void read(int &x){
 9     x=0; register char ch=getchar();
10     while(ch<'0'||ch>'9')ch=getchar();
11     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
12 }
13 int main(){
14     int n;
15     read(n);
16     int st=0,ed=0;
17     int flag=0;
18     for(register int i=1;i<=n;i++){
19         read(temp[i]);
20         if(temp[i]<temp[i-1]){
21             if(st==0){
22                 st=i-1;
23             }
24             a[i]=1;
25         }
26         else if(st){
27             if(!ed)ed=i-1;
28         }
29         if(a[i]!=a[i-1])flag++;
30     }
31     if(flag>2){
32         cout<<"no"<<endl;
33         return 0;
34     }
35     if(!ed&&!st){
36         cout<<"yes"<<endl;
37         cout<<1<<' '<<1<<endl;
38     }
39     else if(!ed){
40         if(temp[n]<temp[st-1]){
41             cout<<"no"<<endl;
42             return 0;
43         }
44         cout<<"yes"<<endl;
45         cout<<st<<' '<<n<<endl;
46         return 0;
47     }
48     else {
49         if(st==1){
50             if(temp[ed+1]>=temp[st]){
51                 cout<<"yes"<<endl;
52                 cout<<1<<' '<<ed<<endl;
53                 return 0;
54             }
55             cout<<"no"<<endl;
56             return 0;
57         }
58         if(ed==n){
59             if(temp[ed]>=temp[st-1]){
60                 cout<<"yes"<<endl;
61                 cout<<st<<' '<<n;
62                 return 0;
63             }
64             cout<<"no"<<endl;
65             return 0;
66         }
67         else {
68             if(temp[st-1]<=temp[ed]&&temp[ed+1]>=temp[st]){
69                 cout<<"yes"<<endl;
70                 cout<<st<<' '<<ed<<endl;
71                 return 0;
72             }
73             cout<<"no"<<endl;
74             return 0;
75         }
76     }
77 }

猜你喜欢

转载自www.cnblogs.com/Fang-Hao/p/9098265.html