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
思路
感觉是道很难的题,想了很久没思路。参考了算法笔记上的贪心策略:对数字串S1和S2,如果S1 + S2 < S2 + S1,就把S1放在S2前面;否则放在S2后面。然后有了点思路,这就像是变相的排序,只不过比的不是数值大小,而是比较拼接起来谁更大。于是我用冒泡排序试写了一下,效果不错,只有最后一个测试点超时,换一种排序方法可能能直接ac。算法笔记上直接用sort解,简洁方便。
超时做法
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<string> vec;
for (int i = 0; i < n; i++)
{
string num;
cin >> num;
vec.push_back(num);
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (vec[j + 1] + vec[j] < vec[j] + vec[j + 1])
{
string tmp = vec[j];
vec[j] = vec[j + 1];
vec[j + 1] = tmp;
}
}
}
string ans = "";
for (int i = 0; i < n; i++)
ans += vec[i];
while (ans.size() > 0 && ans[0] == '0')
ans.erase(ans.begin());
if (ans == "")
cout << 0 << endl;
else
cout << ans << endl;
system("pause");
return 0;
}
直接使用sort
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) { return a + b < b + a; }
int main()
{
int n;
cin >> n;
vector<string> vec;
for (int i = 0; i < n; i++)
{
string num;
cin >> num;
vec.push_back(num);
}
sort(vec.begin(), vec.end(), cmp);
string ans = "";
for (int i = 0; i < n; i++)
ans += vec[i];
while (ans.size() > 0 && ans[0] == '0')
ans.erase(ans.begin());
if (ans == "")
cout << 0 << endl;
else
cout << ans << endl;
system("pause");
return 0;
}