【PAT甲級A1038】Recover the Smallest Number (30分)(c++)
1038 Recover the Smallest Number (30分)
作者:CHEN, Yue
單位:浙江大學
程式碼長度限制:16 KB
時間限制:400 ms
記憶體限制:64 MB
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
題意:
將所給數字組合成最小數。
思路:
用string儲存每個數,在排列的時候我們只要考慮,字串a和b的組合誰大,及cmp函式中,return a+b<b+a;注意,當最後的組合數為0的時候,也要輸出0,不能輸出空。
參考程式碼:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
bool cmp(string a,string b){
return a+b<b+a;
}
int main(){
int n;
string sum;
scanf("%d",&n);
vector<string> v(n);
for(int i=0;i<n;i++)
cin>>v[i];
sort(v.begin(),v.end(),cmp);
for(int i=0;i<n;i++)
sum+=v[i];
while(sum[0]=='0')
sum.erase(sum.begin());
if(!sum.empty())cout<<sum<<endl;
else printf("%d\n",0);
return 0;
}
如有錯誤,歡迎指正
相關文章
- PAT甲級1023 Have Fun with Number
- PAT甲級1126~1130|C++實現C++
- 【PAT甲級A1084】Broken Keyboard (20分)(c++)C++
- PAT甲級1032 Sharing
- PAT甲級1122 Hamiltonian Cycle (25分)|C++實現C++
- PAT甲級1154 Vertex Coloring (25分)|C++實現C++
- PAT甲級1030 Travel Plan
- 浙大PAT甲級考試
- PAT甲級1110 Complete Binary Tree (25分)|C++實現C++
- 【PAT甲級A1065】A+B and C (64bit) (20分)(c++)C++
- PAT甲級-1015. Reversible Primes (20)
- PAT 甲級 1152 Google Recruitment (20分)GoUI
- 20年春季甲級pat考試
- (非原創)PAT甲級1123 Is It a Complete AVL Tree (30分)|C++實現C++
- PAT甲級-1014. Waiting in Line (30)(模擬)AI
- PAT甲級真題1069 數字黑洞(巧妙解法)
- PAT甲級考試題庫題目分類
- 2024 秋季PAT認證甲級(題解A1-A4)
- PAT甲級-1140. Look-and-say Sequence (20)(模擬)
- LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance??LeetCode
- 2021.9.12週六PAT甲級考試覆盤與總結
- 19年春季第二題 PAT甲級 1157 Anniversary(25 分)
- 菜鳥記錄:c語言實現PAT甲級1010--RadixC語言
- 2020年7月第2題 PAT甲級真題 The Judger (25分)
- 夕甲甲——孔乙己之C++版C++
- PAT(甲級)2020年秋季考試 7-1 Panda and PP Milk (20分)
- PAT 乙級
- 【PAT乙級、C++】1024 科學計數法 (20分)C++
- 【PTA甲級、C++簡單解答】1001 A+B Format (20分)C++ORM
- PTA甲級——Be Unique
- PAT乙級1023
- 2019年9月8日秋季PAT甲級題解-2-1161-Merging Linked Lists (25 分)
- 1021 Deepest Root(甲級)
- PAT1013數素數C++C++
- 【PAT乙級】1027 列印沙漏
- 【PAT乙級】1017 A除以B
- 【PAT乙級】1065 單身狗
- 【PAT乙級】1052 賣個萌