FZU-2111-Min Number

J - Min Number
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status

Practice

FZU 2111
Description
Now you are given one non-negative integer n in 10-base notation, it will only contain digits (‘0’-‘9’). You are allowed to choose 2 integers i and j, such that: i!=j, 1≤i

For example, n=9012, we choose i=1, j=3, then we swap n[1] and n[3], then we get 1092, which is smaller than the original n.

Now you are allowed to operate at most M times, so what is the smallest number you can get after the operation(s)?

Please note that in this problem, leading zero is not allowed!

Input
The first line of the input contains an integer T (T≤100), indicating the number of test cases.

Then T cases, for any case, only 2 integers n and M (0≤n<10^1000, 0≤M≤100) in a single line.

Output
For each test case, output the minimum number we can get after no more than M operations.
Sample Input
3
9012 0
9012 1
9012 2
Sample Output
9012
1092
1029

给串数字,给个M,可以交换字符串中的数字,最多交换M次,输出能得到的最小的字符串,注意首位不能是0;

思路:优先处理首位,后面的暴力枚举找最小数,记录下最小数的下标,然后交换。
思路很好想,其实这题考的就是代码能力

代码

#include
#include
#include
#include
#include
#include
#include
using namespace std;
char str[66666];//存储要操作的字符串
int M;//可操作次数
int main()
{
    int T;//T组数据
    scanf("%d",&T);
    while(T--)
    {
        memset(str,'\0',sizeof(str));
        scanf("%s%d",str,&M);
        if(M==0)
        {
            printf("%s",str);
            printf("\n");
            continue;
        }
        int length=strlen(str);
        char min_num;//记录最小数字
        int min_flag;//记录最小数字所在的下标
        char temp;//辅助调整数据
        min_num=str[0];
        for(int i=length-1; i>=0; i--)//优先处理首位,因为首位不能为0
        {
            if(str[i]!='0'&&min_num>str[i])
            {
                min_num=str[i];//寻找最小的数字
                min_flag=i;
            }
        }
        if(min_num!=str[0])//如果需要调整
        {
            temp=str[min_flag];
            str[min_flag]=str[0];
            str[0]=temp;
            M--;//可操作次数减一
        }
        for(int i=1; i0; i++)
        {
            min_num=str[i];//模仿首位,逐个暴力枚举
            for(int j=length-1; j>i; j--)
            {
                if(min_num>str[j])
                {
                    min_num=str[j];
                    min_flag=j;
                }
            }
            if(min_num!=str[i])
            {
                temp=str[min_flag];
                str[min_flag]=str[i];
                str[i]=temp;
                M--;
            }
        }
        printf("%s",str);
        printf("\n");
    }
    return 0;
}

昨晚选拔赛还有一题太简单了,就不写题解了

你可能感兴趣的:(语言入门)