Monday, 21 December 2015

The Next Permutation (UVALive 4556, HDU 3283, POJ 3785, SCU 3485, Regionals 2009 >> North America - Greater NY)

///     Raihan Ruhin
///     CSE, Jahangirnagar University.
///     Dhaka-Bangladesh.
///     id: raihanruhin (topcoder / codeforces / codechef / uva / uvalive), 3235 (lightoj)
///     mail: raihanruhin@ (yahoo / gmail / facebook)
///     blog: ruhinraihan.blogspot.com

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

#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a))
#define PI acos(-1.0)

#define MOD 1000000007
#define MX 100000


int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);
    int tc, kk=1, n, m, x, y, a, b, c, digit[10];
    string s;
    cin>>tc;
    while(tc--)
    {
        cin>>n;
        cin>>s;
        int sl=s.size(), index=-1;

        for(int i=sl-1;i>=0;i--)
        {
            for(int j=sl-1;j>i;j--)
                if(s[j]>s[i])
                {
                    swap(s[i], s[j]);
                    index=i+1;
                    break;
                }
            if(index!=-1) break;
        }
        if(index==-1)    cout<<kk++ <<" BIGGEST\n";
        else
        {
            cout<<kk++<<" ";
            CLR(digit);
            for(int i=index;i<sl;i++)
                digit[s[i]-'0']++;
            for(int i=0;i<index;i++)
                cout<<s[i];
            for(int i=0;i<10;i++)
                while(digit[i]--)
                    cout<<i;
            cout<<"\n";
        }
    }
return 0;
}

No comments:

Post a Comment