-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAlmostSorted.cpp
More file actions
173 lines (149 loc) · 3.72 KB
/
AlmostSorted.cpp
File metadata and controls
173 lines (149 loc) · 3.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// problem: "https://www.hackerrank.com/challenges/almost-sorted/problem"
#include<iostream>
using namespace std;
long long int check_sort (long long int array[100000],long long int n,long long int z)
{
int i;
if(z<0)
z=z+1;
for(i=z;i<n-1;i++)
{
if(array[i]>array[i+1])
{
return i;
}
}
return -1;
}
int main()
{
long long int A[100000],i,j,x,y,n,z,temp;
cin>>n;
for(i=0;i<n;i++)
cin>>A[i];
x=check_sort(A,n,0);
if((x==-1)||(n==2))
{
if(x==-1)
cout<<"yes"<<endl;
else
{
cout<<"yes"<<endl;
cout<<"swap "<<1<<" "<<2<<endl;
}
}
else if(x+1<n-1)
{
if(A[x+1]<A[x+2])
{
y=-1;
for(i=x+1;i<n-1;i++)
{
if(A[i]>A[i+1])
{
y=i+1;
break;
}
}
if(y!=-1)
{
temp=A[x];
A[x]=A[y];
A[y]=temp;
z=check_sort(A,n,x-1);
if(z==-1)
{
cout<<"yes"<<endl;
cout<<"swap "<<x+1<<" "<<y+1<<endl;
}
else
{
cout<<"no"<<endl;
}
}
else
{
temp=A[x];
A[x]=A[x+1];
A[x+1]=temp;
z=check_sort(A,n,x-1);
if(z==-1)
{
cout<<"yes"<<endl;
cout<<"swap "<<x+1<<" "<<x+2<<endl;
}
else
{
cout<<"no"<<endl;
}
}
}
else
{
y=-1;
for(i=x+1;i<n-1;i++)
if(A[i]<A[i+1])
{
y=i;
break;
}
if(y!=-1)
{
if((A[x-1]<A[y])&&(A[x]<A[y+1])&&(x>0))
{
z=check_sort(A,n,y+1);
if(z==-1)
{
cout<<"yes"<<endl;
cout<<"reverse "<<x+1<<" "<<y+1<<endl;
}
else
{
cout<<"no"<<endl;
}
}
else if((A[x]<A[y+1]))
{
z=check_sort(A,n,y+1);
if(z==-1)
{
cout<<"yes"<<endl;
cout<<"reverse "<<x+1<<" "<<y+1<<endl;
}
else
{
cout<<"no"<<endl;
}
}
else
cout<<"no"<<endl;
}
else
{
if((A[n-1]>A[x-1])&&(x>0))
{
cout<<"yes"<<endl;
cout<<"reverse "<<x+1<<" "<<n<<endl;
}
else if(x==0)
{
cout<<"yes"<<endl;
cout<<"reverse "<<x+1<<" "<<n<<endl;
}
else
cout<<"no"<<endl;
}
}
}
else
{
if(A[x-1]<A[x+1])
{
cout<<"yes"<<endl;
cout<<"swap "<<x+1<<" "<<x+2<<endl;
}
else
cout<<"no"<<endl;
}
return 0;
}