The Next Permutation(UVALive 4556,模拟)

Description

For this problem, you will write a program that takes a (possibly long) string of decimal digits, and outputs the permutation of those decimal digits that has the next larger value (as a decimal number) than the input number. For example:

123 -> 132

279134399742 -> 279134423799

              It is possible that no permutation of the input digits has a larger value. For example, 987.

Input

The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by up to 80 decimal digits which is the input value.

Output

For each data set there is one line of output. If there is no larger permutation of the input digits, the output should be the data set number followed by a single space, followed by the string ‘BIGGEST’. If there is a solution, the output should be the data set number, a single space and the next larger permutation of the input digits.

Sample Input

3

1 123

2 279134399742

3 987

Sample Output

1 132

2 279134423799

3 BIGGEST

题解:

从最后一位往前遍历求解第一个递减的数,与此位数后面的比这位大的最小数交换,再将此位数后面的数排序(升序),这样组成的数为大于原数的最小数。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#define max(a,b)   (a>b?a:b)
#define min(a,b)   (a<b?a:b)
#define swap(a,b)  (a=a+b,b=a-b,a=a-b)
#define maxn 320007
#define N 100000000
#define INF 0x3f3f3f3f
#define mod 1000000009
#define e  2.718281828459045
#define eps 1.0e18
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define memset(x,y) memset(x,y,sizeof(x))
#define Debug(x) cout<<x<<" "<<endl
#define lson i << 1,l,m
#define rson i << 1 | 1,m + 1,r
#define ll long long
//std::ios::sync_with_stdio(false);
//cin.tie(NULL);
using namespace std;

char a[100];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int m;
        cin>>m>>a;
        int l=strlen(a),i;
        for(i=l-1;i>=1;i--)
        {
            if(a[i-1]<a[i])
                break;
        }
        if(i==0)
        {
            cout<<m<<" BIGGEST"<<endl;
            continue;
        }
        //cout<<a[i-1]<<endl;
        int k=i,minn=INF;
        for(int j=i;j<l;j++)
            if(minn>a[j]&&a[i-1]<a[j])
            {
                minn=a[j];
                k=j;
            }
        //cout<<a[k]<<endl;
        swap(a[k],a[i-1]);
        sort(a+i,a+l);
        cout<<m<<" "<<a<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值