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

被折叠的 条评论
为什么被折叠?



