码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Digits

时间:2014-11-25 09:20:31      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:des   style   io   ar   color   os   sp   for   strong   

Description

Now we have a number, you can swap any two adjacent digits of it, but you can not swap more than K times. Then, what is the largest probable number that we can get after your swapping?

Input

There is an integer T (1 <= T <= 200) in the first line, means there are T test cases in total.

For each test case, there is an integer K (0 <= K < 106) in the first line, which has the same meaning as above. And the number is in the next line. It has at most 1000 digits, and will not start with 0.

There are at most 10 test cases that satisfy the number of digits is larger than 100.

Output

For each test case, you should print the largest probable number that we can get after your swapping.

Sample Input

3
2
1234
4
1234
1
4321

Sample Output

3124
4213
4321

<span style="color:#330033;"># include <cstdio>
# include <cstring>
# include <iostream>
using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int k,i,j,a=0,n,cnt=0;char c[1100],x,Max='.';
        scanf("%d%s",&k,c);
        while(k>1&&a<strlen(c))    //跳出循环条件;k=1时分开讨论;
        {
            if(a+k+1>strlen(c))   n=strlen(c);
            else   n=a+k+1;
            for(i=a+1;i<n;i++)    //找出区间内最大值;
                if(c[i]>c[a]&&c[i]>Max)  { Max=c[i];   j=i; cnt=j-a; }   //cnt记住移了多少次;
            if(Max=='.')   a++;
            else    //更新字符数组;
            {
                for(i=j;i>j-cnt;i--)    c[i]=c[i-1];
                c[a]=Max;
                Max='.';
                k-=cnt;
                a++;
            }
        }
        if(k==1)
        {
            while(c[a]>=c[a+1]&&strlen(c)>(a+1))   a++;
            if(c[a]<c[a+1])
            {
                x=c[a];
                c[a]=c[a+1];
                c[a+1]=x;
            }
        }
        puts(c);
    }
    return 0;
}</span>

Swap Digits

标签:des   style   io   ar   color   os   sp   for   strong   

原文地址:http://blog.csdn.net/rechard_chen/article/details/41458347

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!