1038. Recover the Smallest Number (30)
来源:互联网 发布:php 扩展 不成功 编辑:程序博客网 时间:2024/05/21 05:37
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;}
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)-PAT
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- PAT 1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 【PAT】1038. Recover the Smallest Number (30)
- 1038. Recover the Smallest Number (30)
- 常用算法:分治算法、动态规划算法、贪心算法、回溯法、分支限界法
- [译] Twitter数据挖掘:如何使用Python分析大数据
- ie浏览器跟各个浏览器兼容
- 详解python linecache模块读取文件的方法
- 一.Python环境安装
- 1038. Recover the Smallest Number (30)
- 消息池
- Java集合作业
- inline-block在ie兼容性问题
- 简述设计模式之单例模式
- Codeforces Round #430 (Div. 2) C. Ilya And The Tree(dfs+最大公约数+因子+树)
- 深入分析Java ClassLoader原理
- 字体样式
- 游戏开发之U3D实现技能图标冷却的效果