1038. Recover the Smallest Number (30)

本文介绍了一个算法问题,即从给定的一系列数字段中找出能够组成最小数字的组合方式。通过使用贪心策略,对数字段进行特定排序,并考虑首位为0的特殊情况,最终输出最小的数字。

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (<=10000) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Do not output leading zeros.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

算法解析:采用贪心算法,把各个数字两两组合,按照组合起来的数字由小到大排序,然后再看顺序输出。这里要注意的是首位不能是0,除非要输出的数就是0。最关键的就是组合如何排序,只要用cmp()函数就能实现,具体的见代码部分。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *a, const void *b) //构造比较组合大小的比较器
{
    char ab[20] = {'\0'}, ba[20] = {'\0'};
    strcpy(ab, (char*)a);
    strcpy(ba, (char*)b);
    strcat(ab, (char*)b);
    strcat(ba, (char*)a);
    return strcmp(ab, ba);
}

int main()
{
    int n, i, j;
    char collection[10000][9] = {{'\0'}};
    scanf("%d", &n);
    for(i = 0; i < n; i++)
        scanf(" %s", collection[i]);
    qsort(collection, n, sizeof(collection[0]), cmp); //实现排序
    int flag = 1;
    for(i = 0; i < n; i++)
    {
        int len = strlen(collection[i]);
        for(j = 0; j < len; j++)
        {
            if(collection[i][j] == '0' && flag == 1) //如果第首位输出的数字是0,那么就不输出
                continue;                        //此处代码可以化简,但为了逻辑清晰,还是这么写
            else //当输出第一个不为0的数,即保证了首位不为0,就把flag清零。
            {
                printf("%c", collection[i][j]);
                flag = 0;
            }
        }
    }
    if(flag == 1) //如果得到的数为0,就输出0
        printf("0");

    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值