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
给出若干个数,求他们能组成的最小的数。其实就是用排序。关键是比较函数。两个数对比对应的位,如果有不一样的位,则这个位较小的那个数优先级较高(比如5和32,32优先级比5高,因为组成的数325比532小),如果直到某个数到了结尾还没分出大小,则要延长该数来对比(为什么延长看看例子就能意会),比如32和321,将32延长成323,故321优先级较高(这两个数能组成32321和32132,32132比较小)。有了比较函数就能进行排序,用sort函数。最后输出结果,注意前面的0不能输出。这里还要注意可能最后的结果可能为0。
代码:
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
bool cmp(string s1,string s2)
{
int n=s1.size(),m=s2.size();
if(n<=m)
{
while(n<m)
{
s1=s1+s1.substr(0,(m-n<=n)?m-n:n);
n=s1.size();
}
}
else
{
while(m<n)
{
s2=s2+s2.substr(0,(n-m<=m)?n-m:m);
m=s2.size();
}
}
for(int i=0;i<n;i++)
{
if(s1[i]!=s2[i]) return s1[i]<s2[i];
}
return true;
}
int main()
{
int n;
cin>>n;
vector<string>nums(n);
for(int i=0;i<n;i++)
{
cin>>nums[i];
}
sort(nums.begin(),nums.end(),cmp);
bool flg=true;
for(int i=0;i<nums.size();i++)
{
for(int j=0;j<nums[i].size();j++)
{
if(flg&&nums[i][j]=='0') continue;
cout<<nums[i][j];
flg=false;
}
}
if(flg) cout<<0;
}
9.10更新
发现以前的cmp函数写复杂了,这里更新比较简单的。
bool cmp(const string& s,const string& t)
{
return s+t<t+s;
}