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
题目大意:给出N个非负整数,每个非负整数不超过8个数字,求这些非负整数可以拼接成的最小的数;
分析:这题目用贪心的思想,每次都选出使得拼接结果最小的非负整数;那么如何挑选呢?
对于3214 0229这两个数,我们肯定把0229放在前面,因为总的位数是固定的,0229放前面,首位数字最小,总数最小;
那么对于321 32这两个数呢,我们可以知道321 32比32 321要小,所以321要放前面;我看可以这么比较,既然前两位相等,那么继续比较第三位,32没有第三位啊,没关系啊,我们可以3%2=1,即用32的第一位数3继续去比较,321的第三位1比3要小,所以321排在前面;
当然这里有一种情况不能忽略,即321 321321这两个数,如果让他比较的话,会一直持续下去;假设数字a,b的长度分别为La,Lb,比较La,Lb的公倍数位即可;如果比较了这么多位,还是相等,则谁在前对结果没影响;
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a%b);
}
int lcm(int a, int b) {return a * b / gcd(a, b);}
bool cmp(const string& A, const string& B){
if (A == B)
return A < B;
else{
int index = 0;
int lenA = A.length();
int lenB = B.length();
while (index < lcm(lenA,lenB)){
if (A[index%lenA] < B[index%lenB])
return true;
if (A[index%lenA] > B[index%lenB])
return false;
index++;
}
}
return A.length() < B.length();
}
vector<string>V;//存放各个数字
int N;
string ret;
int main(){
scanf("%d", &N);
V.resize(N);
for (int i = 0; i < N; i++)
cin >> V[i];
sort(V.begin(), V.end(), cmp);
for (auto it = V.begin(); it != V.end(); it++)
ret += *it;
while (ret.length() > 1 && ret[0] == '0')
ret.erase(ret.begin());
cout << ret;
return 0;
}
Update2.0
上面的解题思路还是太绕了,柳神的思路化繁为简,太精彩了,参考了柳神代码如下:1038. Recover the Smallest Number (30)-PAT甲级真题(贪心算法)
其实判断数字a,b拼凑成的数字ab还有ba那个大,直接用拼接之后的字符串比较大小就可以;即如果字符串比较ab<ba,则ab表示的数小于ba表示的数;
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
bool cmp(const string& A, const string& B) { return A + B < B + A; }
vector<string>V;
int N;
string ret;
int main(){
scanf("%d", &N);
V.resize(N);
for (int i = 0; i < N; i++)
cin >> V[i];
sort(V.begin(), V.end(), cmp);
for (auto it = V.begin(); it != V.end(); it++)
ret += *it;
while (ret.length() > 1 && ret[0] == '0')
ret.erase(ret.begin());
cout << ret;
return 0;
}