1038 Recover the Smallest Number (30 分)PAT (Advanced Level) Practice
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
題目大意:給一些字串,求它們拼接起來構成最小數字的方式分析:貪心演算法。讓我們一起來見證cmp函式的強大之處!!~~不是按照字典序排列就可以的,必須保證兩個字串構成的數字是最小的才行,所以cmp函式寫成return a + b < b + a;的形式,保證它排列按照能夠組成的最小數字的形式排列。因為字串可能前面有0,這些要移除掉(用s.erase(s.begin())就可以了~嗯~string如此神奇~~)。輸出拼接後的字串即可。注意:如果移出了0之後發現s.length() == 0了,說明這個數是0,那麼要特別地輸出這個0,否則會什麼都不輸出~
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp0(string a, string b) {
return a + b < b + a;
}
string str[10010];
int main() {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
cin >> str[i];
sort(str, str + n, cmp0);
string s;
for(int i = 0; i < n; i++)
s += str[i];
while(s.length() != 0 && s[0] == '0')
s.erase(s.begin());
if(s.length() == 0) cout << 0;
cout << s;
return 0;
}
#include<iostream>
#include <vector>
#include <algorithm>
#include<string>
using namespace std;
int cmp(string a,string b)
{
return a+b<b+a;//升序排
}
string str[10010];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
cin>>str[i];
sort(str,str+n,cmp);
string s;
for(int i=0;i<n;i++)
s=s+str[i];
int j=0;
for(;j<s.length();j++)
if(s[j]!='0')break;
if(j==s.length())cout<<0;
else
{
for(;j<s.length();j++)
cout<<s[j];
}
return 0;
}