Minimum Good Permutation - MINPERM CodeChef Easy Question

Welcome back !
Here is the link to today's PROBLEM

So , the question is simple enough , we just need to find a perumtation of 1 to n where pi != i and is smallest .
So , what we do is we make two cases.

If the length is even we just swap two adjacent elements in pairs , like 1,2 to 2,1 1,2,3,4 to 2,1,4,3 and so on..
If the lenght is odd , we swap adjacent elements amd in the end swap nth and n-1th pair . Eg. 1,2,3 to 2,1,3 and then finally 2,3,1
1,2,3,4,5 to 2,1,4,3,5 and then 2,1,4,5,3.

Here is the Code for that :-

Code :-

#include <iostream>
using namespace std;

int main() {
    int t;
    scanf("%d",&t);
    while(t--)
    {
        long n;
        scanf("%ld",&n);
        long arr[n];
        long i=0;
        if(n%2==0)
        {
            while(i!=n)
            {
                arr[i]=i+1+1;
                arr[i+1]=i+1;
                i=i+2;
            }
        }
        else
        {
            while(i!=n+1)
            {
                arr[i]=i+1+1;
                arr[i+1]=i+1;
                i=i+2;
            }
            arr[n-1]--;
            long k;
            k=arr[n-2];
            arr[n-2]=arr[n-1];
            arr[n-1]=k;
            
            
        }
        i=0;
        while(i!=n)
        {
            cout<<arr[i]<<" ";
            i++;
        }
        cout<<endl;
    }
// your code goes here
return 0;
}


Do follow my blog and post your doubts and queries in the comments section .


Comments

Popular Posts