magnus_89's blog

By magnus_89, history, 3 months ago, In English

hey what's up guyz. Hope you all are doing great. I am facing difficulties to solve this problem, although I have understood the problem but I couldn't implement an optimal approach can someone write the code of this problem with explaining each part. I know that it is a very basic level problem but I just started CP that's why I am stuck on that problems. I will be very grateful if someone figure it out. Thanks for reading :)

  • Vote: I like it
  • -6
  • Vote: I do not like it

»
3 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
/*
We are allowed to reverse exactly one subarray [l, r].
Our goal is to make the permutation lexicographically maximum.

To maximize a permutation lexicographically:
- We want the largest possible number at the earliest position.
- The ideal target permutation would be:
  n, n-1, n-2, ..., 2, 1

So the idea is:
1) Create an "ideal" permutation in descending order.
2) Compare the given permutation with the ideal one.
3) Find the first index where the given array is smaller than the ideal array.
   This index is the position where we can improve the permutation (l).
4) The value that should be at position l is ideal[l].
   We search for this value in the array to the right and take its last position as r.
5) Reverse the subarray from l to r.
   This brings the largest possible value to index l, giving the lexicographically
   maximum permutation using exactly one reverse operation.
*/

#include<bits/stdc++.h>
using namespace std;

#define int long long
#define yy cout<<"YES"<<endl
#define nn cout<<"NO"<<endl

void solve(){
    int n;
    cin>>n;
    vector<int> a(n);
    for(int i=0;i<n;i++)cin>>a[i];
    vector<int> ideal; // This will contain [n,n-1,n-2,...,3,2,1]

    int l = n-1; // Find first index where improvement is possible
    for(int i=n;i>0;i--)ideal.push_back(i);
    for(int i=0;i<n;i++){
        if(ideal[i]>a[i]){
            l=i;
            break;
        }
    }

    int curr = ideal[l]; // Find the value that should be placed at index l

    // Find the last position of curr after l
    int r = l;
    for(int i=l+1;i<n;i++){
        if(a[i]==curr){
            r=i;
        }
    }

    // reverse the segment
    reverse(a.begin()+l,a.begin()+r+1);

    
    for(int i=0;i<n;i++)cout<<a[i]<<" ";
    cout<<endl;
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    int t = 1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}