CSU 1270: Swap Digits(数学啊 )

题目链接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1270


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

HINT

Source

中南大学第七届大学生程序设计竞赛


题意:

交换相邻的数字 k 步,能得到的最大的数!

PS:

设一个临时起点,每次从临时起点开始剩余的步数之内最大的数与设立的临时起点的数交换,临时起点向后移一位;

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int t;
    int k;
    char s[1017];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%s",&k,s);
        int len = strlen(s);
        int pos = 0;
        int cont = 0;
        while(k)
        {
            int maxx = s[pos]-'0', p = pos;
            int LEN = pos+k > len ?len-1: pos+k;
            for(int i = pos+1; i <= LEN; i++)
            {
                int tt = s[i]-'0';
                if(tt > maxx)//区间最大的
                {
                    maxx = tt;
                    p = i;
                }
            }
            k -= (p-pos);
            char c = s[p];
            for(int i = p-1; i >= pos; i--)
            {
                s[i+1] = s[i];
            }
            s[pos] = c;
            //if(p != pos)
            pos++;
            if(pos >= len)
                break;
        }
        printf("%s\n",s);
    }
    return 0;
}
/*
99
2
1234
4
1234
1
4321
6
4256
*/


你可能感兴趣的:(数学,CSU)