Almost Sorted

Given an array of integers, determine whether the array can be sorted in ascending order using only one of the following operations one time.

  1. Swap two elements.
  2. Reverse one sub-segment.

Determine whether one, both or neither of the operations will complete the task. Output is as follows.

  1. If the array is already sorted, output yes on the first line. You do not need to output anything else.

  2. 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.

  1. 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<intarr)
{
    //if the array is already sorted
    //then print yes
    if (is_sorted(arr.begin(), arr.end()))
    {
        cout << "yes";
        return;
    }
    int firstlast;

    //find the firts element which is not
    //in the increasing order
    for (int i = 0i < arr.size() - 1i++)
        if (arr[i] > arr[i + 1])
        {
            first = i;
            break;
        }
    //similarly find the last element
    //which is not in proper sequence
    for (int i = arr.size() - 1i > 0i--)
        if (arr[i - 1] > arr[i])
        {
            last = i;
            break;
        }

    //swap both the elements
    swap(arr[first]arr[last]);

    //if array is sorted then print yes
    //and position of swapped element
    if (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 array
    swap(arr[first]arr[last]);

    //reverse array from position first to last
    reverse(arr.begin() + firstarr.begin() + last + 1);

    //if array is sorted then print yes and
    // reverse positions
    if (is_sorted(arr.begin(), arr.end()))
    {
        cout << "yes" << endl
             << "reverse " << first + 1 << " " << last + 1;
        return;
    }

    //otherwise not possible to make array sorted by
    //these operations
    cout << "no";
}

int main()
{

    int n = 6;
    vector<intarr = {154326};
    almostSorted(arr);

    return 0;
}


No comments:

Post a Comment