【PAT甲级】Recover the Smallest Number
- 2019 年 11 月 8 日
- 筆記
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/89716717
Problem Description:
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 (≤104) 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. Notice that the first digit must not be zero.
Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287
解题思路:
建立一个vector用来存放string型的数字,自定义一个比较规则cmp来使数字构成的字符串经可能小,然后以cmp为比较规则来对vector进行sort。接着判断字符串是不是以0开头,若字符串以0开头则需要删除0。然后判断字符串是不是为空(即字符串长度是否为0),若字符串str为空,则令str = "0",最后输出str即可。
AC代码:
#include <bits/stdc++.h> using namespace std; bool cmp(string s1,string s2) //使数字构成的字符串要尽可能小 { return s1+s2 < s2+s1; } int main() { int N; cin >> N; vector<string> v; for(int i = 0; i < N; i++) { string temp; cin >> temp; v.push_back(temp); } sort(v.begin(), v.end(),cmp); string str = ""; for(auto it : v) { str += it; } int len = str.length(); while(len !=0 & str[0] == '0') //一大串数字组成的字符串第一个数字不能为0 { str.erase(str.begin()); } if(len == 0) { str = "0"; } cout << str << endl; return 0; }