|
| 1 | +#include<bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +int mod=1e9+7; |
| 5 | +#define F(a,b,var) for(int var=a;var<b;var++) |
| 6 | +#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) |
| 7 | + |
| 8 | +void almost_sorted(vector<int> &sequence){ |
| 9 | + //edgecases |
| 10 | + if(sequence.size() < 2){ |
| 11 | + cout<<"Yes\n"; //since less than 2 means it can be reversed as well as swapped |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + if(is_sorted(sequence.begin(), sequence.end())){ |
| 16 | + cout<<"Yes\n"; //already sorted |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + //vector is partially sorted.. |
| 21 | + int N = sequence.size(); |
| 22 | + int i = 0, j = sequence.size() - 1; |
| 23 | + |
| 24 | + while(i != N && sequence[i+1] > sequence[i]) |
| 25 | + i++; //find start of partial array where it breaks the sorted sequence |
| 26 | + while(j >= 0 && sequence[j-1] < sequence[j]) |
| 27 | + j--; //find end of partial array where it breaks the sorted sequence |
| 28 | + |
| 29 | + //start and end of unsorted - subarray |
| 30 | + swap(sequence[i], sequence[j]); |
| 31 | + if(is_sorted(sequence.begin(), sequence.end())){ |
| 32 | + cout<<"yes\n"; //partial is now sorted |
| 33 | + cout<<"swap "<<(i+1)<<" "<<(j+1)<<"\n"; |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + int k = i + 1, l = j - 1; |
| 38 | + while(k < l){ |
| 39 | + swap(sequence[k], sequence[l]); //keep swapping the entire partial array .. basically reversing the array |
| 40 | + k++, l--; |
| 41 | + } |
| 42 | + |
| 43 | + if(is_sorted(sequence.begin(), sequence.end())){ |
| 44 | + cout<<"yes\n"; //partial is now sorted |
| 45 | + cout<<"reverse "<<(i+1)<<" "<<(j+1)<<"\n"; |
| 46 | + return; |
| 47 | + } |
| 48 | + else{ |
| 49 | + cout<<"no\n"; // it is not possible to make the array properly sorted.. |
| 50 | + return; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +int main() { |
| 55 | + //code |
| 56 | + FAST_INP; |
| 57 | + int n; |
| 58 | + cin>>n; |
| 59 | + |
| 60 | + vector<int> seq(n); |
| 61 | + for(int i = 0; i < n; i++) |
| 62 | + cin>>seq[i]; |
| 63 | + |
| 64 | + almost_sorted(seq); |
| 65 | + return 0; |
| 66 | +} |
0 commit comments