Friday, March 22, 2019

JNEXT : Just Next !!!

JNEXT : Just Next !!!

Link for the problem: JNEXT

Problem:
The problem asks you to print the just next permutation of the given sequence of digits. If next permutation is not possible then you have to print '-1'.

Solution:

> There will be always a possible next permutation, if for any digit at index i there is another greater digit than ith digit and lies to the right of i.
> If the above is not true for any index i, then the answer will be -1, i.e. there is no possible next permutation.
> To find next permutation, we have to find first index i from right.
> After finding above index, swap it with the element which lies to the right and is just greater than that element.
(see code for more clarification)
> After swapping, sort rest right part of the sequence (excluding that element).
>print the sequence.

Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        int a[n],i,j,k;
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        int f=0;
        for(i=n-1;i>=1;i--)
        {
            if(a[i]>a[i-1])
            {
                f=1;
                break;
            }
        }
        if(f){
        int m=i;
        for(j=i+1;j<n;j++)
        {
            if(a[j]<a[m]&&a[j]>a[i-1])
            m=j;
        }
        k=a[i-1];
        a[i-1]=a[m];
        a[m]=k;
        sort(a+i,a+n);
        for(i=0;i<n;i++)
        printf("%d",a[i]);}
        else
        printf("-1");
        printf("\n");
    }
    return 0;

}


STL Method:

This problem can be solved by using STL in C++. The function used is next_permutation(). If Next permutation is not possible then it returns 'False' else 'True' and you have to just print the sequence.
(see Code)

CODE:

#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
    int n;
    scanf("%d",&n);
    int a[n],i,j,k;
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    bool v=next_permutation(a,a+n);
    if(v==false)
    printf("-1");
    else
    {
        for(i=0;i<n;i++)
        printf("%d",a[i]);
    }
    printf("\n");
}
return 0;

}

No comments:

Post a Comment

CHEFST: Chef and the stones

CHEFST: Chef and the stones Link for the problem:  CHEFST SOLUTION: For a given max possible no of stones that can be removed from ea...