-
Notifications
You must be signed in to change notification settings - Fork 0
/
almost_sorted.cpp
95 lines (85 loc) · 2.19 KB
/
almost_sorted.cpp
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
/*
* https://www.hackerrank.com/challenges/almost-sorted/problem
*/
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n;
cin >> n;
int *arr = new int[n+1];
arr[n] = 1000001;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
int *start = NULL;
int *end = NULL;
int flag = 0;
for (int i = 1; i < n; ++i) {
if (arr[i] < arr[i-1]) {
if (flag == 0) { //beginning
start = &arr[i-1]; //prev
flag = 1;
}
end = &arr[i];
}
else if (flag == 1) {
break;
}
}
//cout << *start << endl;
if (start == NULL) {
cout << "yes" << endl;
return 0;
}
int size = (int)(end-start+1);
//cout << "size: " << size << endl;
if (size > 2) { //one solution (Reversing)
int *tmp_start = start;
int *tmp_end = end;
while (tmp_start < tmp_end) {
int tmp = *tmp_end;
*tmp_end = *tmp_start;
*tmp_start = tmp;
tmp_start++;
tmp_end--;
//cout << "indecies " << (int)(tmp_start-arr+1) << " " << (int)(tmp_end-arr+1) << endl;
}
}
else {
if (*(end+1) < *start) { //looking for not adjacent swaps
int *tmp = end;
while (++end <= &arr[n]) {
if (*end < *tmp) { //found a swap
int swap = *start;
*start = *end;
*end = swap;
break;
}
}
}
else {
int swap = *end;
*end = *start;
*start = swap;
}
}
for (int i = 1; i < n; ++i) {
//cout << arr[i] << endl;
if (arr[i] < arr[i-1]) {
//cout << arr[i-1] << " " << arr[i] << endl;
cout << "no" << endl;
return 0;
}
}
cout << "yes" << endl;
if (size > 2) {
cout << "reverse " << (int)(start-arr+1) << " "
<< (int)(end-arr+1) << endl;
}
else {
cout << "swap " << (int)(start-arr+1) << " "
<< (int)(end-arr+1) << endl;
}
}