PAT_A 1038 Recover the Smallest Number
PAT_A 1038 Recover the Smallest Number
分析
题意为将N个数字相连接成为一个新数字,求新数字最小的连接情况。
可通过排序将输入序列转换为一个新序列。显然,对于两数字a、b及连接运算 +,若 a+b < b+a 则a应排在b之前,推广至整个序列仍成立。因此排序后按序输出即可。
需要注意最后合成的新数字是不含前导0的。因此需要对于含有多个 0 元素(例如0, 00等)的输入;以及全0的输入做相应处理。
PAT_A 1038 Recover the Smallest Number
题目的描述
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 (≤10^4)$ 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
AC的代码
#include<bits/stdc++.h>
using namespace std;
bool cmp(string a,string b){
return stoll(a+b)<stoll(b+a);
}
int main(){
int N;
scanf("%d",&N);
vector<string> num(N);
for(int i=0;i<N;i++){
cin>>num[i];
}
sort(num.begin(),num.end(),cmp);
bool f=false;
int j=0;
while(!f && j<N){
for(int i=0;i<num[j].length();i++){
if(num[j][i]=='0'&&!f)continue;
cout<<num[j][i];
f=true;
}
j++;
}
for(int i=j;i<N;i++){
cout<<num[i];
f=true;
}
if(!f)cout<<'0';
cout<<endl;
return 0;
}
本文来自博客园,作者:ghosteq,转载请注明原文链接:https://www.cnblogs.com/ghosteq/p/16691733.html