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 (<=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 87
Sample Output:
22932132143287
大致题意为:给出 {32, 321, 3214, 0229, 87}这样的数字片段,组合这些数字片段成为一个数,如32-321-3214-0229-87这个组合就是323213214022987这个数,要求输出最小的组合数。
分析:
显而易见的是需要用string存储,数字长度太长,任何类型的int都不足以存储。
个人思路:用sort()排序解决,须写好cmp比较函数,主要思想如下:
归纳总结后,两者比较的关系如图,长短相同的字符串不再讨论,直接return a < b 即可; 对于长短不一的两个字符串,如上图,”长字符串%短字符串.size() 和 短字符串相应位置元素”进行比较。第一轮如绿线所示,若出现不等情况就可return 0或1,相等继续比较,如蓝线所示,直到遍历完整个a字符串。
经典算法:私以为自己的方法足够好了,结果在网上看到了更为简洁的cmp比较函数:
bool cmp(const string& a,const string& b){return a + b< b + a;}
其实这道题cmp比较函数就是要区分a+b和b+a这两个串哪个大,该思路从宏观上解决,简洁易懂。
完整代码:
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include <cmath>
#include <algorithm>
using namespace std;
vector<string> tab;
bool cmp(string a, string b)
{
return a + b < b + a;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
string temp;
cin >> temp;
tab.push_back(temp);
}
sort(tab.begin(), tab.end(), cmp);
string output="";
for (int i = 0; i < tab.size(); i++)
{
output += tab[i];
}
while (output[0] == '0')output.erase(0, 1);
if (output == "")output = "0";
cout << output << endl;
return 0;
}