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 (<=10000) 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. Do not output leading zeros.
Sample Input:5 32 321 3214 0229 87Sample Output:
22932132143287
解题思路:就是尽量将小的数字开始的数放在前面,让小的数字占据高位,最后形成的数也就越小。
注意点:一开始写程序的时候,我在输入的时候就将以0为开头的数字直接将0去掉之后存放在向量中,因为我认为是每个数字实际的值在进行组合,但是后来提交一直错误,尝试改了一下,发现是这个问题,这个题对于 2 01 02 的输入正确输出应该是102而不是我之前想的12.
后来我看到别人写的一个比较函数,比我的简单多了,我要进行那么多的判断,别人两行就解决了。#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; bool cmp(const string ss1, const string ss2){ int index = 0; string s1 = ss1,s2 = ss2; if (s1.length() < s2.length()){ while (s1.length() < s2.length()){ s1 = s1 + ss1; } } else if (s1.length() > s2.length()){ while (s2.length() < s1.length()){ s2 = s2 + ss2; } } while (index < s1.length() && index < s2.length()){ if (s1[index] < s2[index]){ return true; } else if (s1[index] > s2[index]){ return false; } else{ index++; } } return true; } int main(){ for (int n; cin >> n;){ vector<string>vec; while (n--){ string s; cin >> s; vec.push_back(s); } sort(vec.begin(), vec.end(), cmp); string res = ""; res += vec[0]; for (int i = 1; i < vec.size(); i++){ res += vec[i]; } if (res.find_first_not_of('0') != -1){ cout << res.substr(res.find_first_not_of('0'))<<endl; } else{ cout << "0" << endl; } } return 0; }bool cmp(const string s1, const string s2){ return s1 + s2 < s2 + s1; }
本文详细介绍了如何从一组数字段中找到最小组合的方法,并分析了常见的优化策略。通过对比不同实现方式,揭示了效率提升的关键点。此外,文章还讨论了在处理以0开头的数字时的常见陷阱及解决方案。
322

被折叠的 条评论
为什么被折叠?



