【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; }