【PAT甲級A1038】Recover the Smallest Number (30分)(c++)

小莊同學發表於2020-11-15

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 (≤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

題意:

將所給數字組合成最小數。

思路:

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

如有錯誤,歡迎指正

相關文章