1038 Recover the Smallest Number (30 分)
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
提交次數 | 通過樣例 | 分數 | tips |
---|---|---|---|
1 | 6/7 | 28 | 未注意全零時的輸出 |
2 | all | 30 |
NOTE
- 整型(int)最大值:2147483647 (10位十進制數)
長整型最大值:9223372036854775807 (19位十進制數) - 題目中說最大數不超過8位,因此使用長整型也是可以的;但在此題中,無論是比較大小還是前導零的處理,都是用string要方便些
- 注意vector,當給vector賦值了大小時,有些操作就與之前不一樣,比如不能使用
push_back()
;sort時也不能用sort(v.begin(), v.end())
這種格式等等,前面有一次題解也總結了一些,還是要繼續觀察,並記住,以在考場中節省時間 - 思路是將所有數字放入vector中,並進行排序輸出;重點在於怎樣排序:
- 這裏並不完全是按字典序進行排
- 而是兩字符串a和b比較的時候(即cmp函數),
a+b
和b+a
進行字典序排序,比如
32 和 321 比較 常規字典序比較是:32 < 321 實際上組合之後:321-32 比 32-321 要小
- 輸出時,注意前導零不能輸出,題目給定的數是
non negative
,即非負數,則題目中有可能有0的存在,數目不定,因此不能只判定第一個數字的輸出,而是直到找到第一個非零數之前都要進行前導零的判斷 - 別忘了全爲零時要輸出0
code
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
vector<string> v(maxn);
bool flag = false;
void print(string s)
{
int i;
for(i = 0; i < s.size(); i++){
if(s[i] != '0') break;
}
for( ; i < s.size(); i++){
cout << s[i];
flag = true; //到了第一個不爲0的位置
}
}
bool cmp(string a, string b)
{
return a + b < b + a;
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++){
cin >> v[i];
}
sort(v.begin(), v.begin() + n, cmp); //當對vector賦值了大小時,不能使用sort(v.begin(), v.end())這種形式
for(int i = 0; i < v.size(); i++){
if(!flag) print(v[i]);
else cout << v[i];
}
if(!flag) cout << "0";//別忘了爲0的時候
return 0;
}