Given an array of integers, determine whether the array can be sorted in ascending order using only one of the following operations one time.
- Swap two elements.
- Reverse one sub-segment.
Determine whether one, both or neither of the operations will complete the task. Output is as follows.
If the array is already sorted, output yes on the first line. You do not need to output anything else.
If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:
- If elements can only be swapped, and , output swap l r in the second line. and are the indices of the elements to be swapped, assuming that the array is indexed from to .
- If elements can only be reversed, for the segment , output reverse l r in the second line. and are the indices of the first and last elements of the subarray to be reversed, assuming that the array is indexed from to . Here represents the subarray that begins at index and ends at index , both inclusive.
If an array can be sorted both ways, by using either swap or reverse, choose swap.
- If the array cannot be sorted, either way, output no on the first line.
Example:
Input: n = 6, arr = {1, 5, 4, 3, 2, 6}
Output:
yes reverse 2 5
Approach:
C++
#include <bits/stdc++.h>using namespace std;void almostSorted(vector<int> arr){//if the array is already sorted//then print yesif (is_sorted(arr.begin(), arr.end())){cout << "yes";return;}int first, last;//find the firts element which is not//in the increasing orderfor (int i = 0; i < arr.size() - 1; i++)if (arr[i] > arr[i + 1]){first = i;break;}//similarly find the last element//which is not in proper sequencefor (int i = arr.size() - 1; i > 0; i--)if (arr[i - 1] > arr[i]){last = i;break;}//swap both the elementsswap(arr[first], arr[last]);//if array is sorted then print yes//and position of swapped elementif (is_sorted(arr.begin(), arr.end())){cout << "yes" << endl<< "swap " << first + 1 << " " << last + 1;return;}//if not sorted then again swap//previously swappped element to get//back into the orginal arrayswap(arr[first], arr[last]);//reverse array from position first to lastreverse(arr.begin() + first, arr.begin() + last + 1);//if array is sorted then print yes and// reverse positionsif (is_sorted(arr.begin(), arr.end())){cout << "yes" << endl<< "reverse " << first + 1 << " " << last + 1;return;}//otherwise not possible to make array sorted by//these operationscout << "no";}int main(){int n = 6;vector<int> arr = {1, 5, 4, 3, 2, 6};almostSorted(arr);return 0;}
No comments:
Post a Comment