Recover the Smallest Number (30)

来源:互联网 发布:阿里云解析新网域名 编辑:程序博客网 时间:2024/05/17 09:10

题目描述

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.

输入描述:

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.


输出描述:

For each test case, print the smallest number in one line.  Do not output leading zeros.

输入例子:

5 32 321 3214 0229 87

输出例子:

22932132143287

解题思路:采用两个数之间交换比大小的方式来进行排序(x+y<y+x)。
注意点:n=1时。

我的代码:
#include<iostream>#include<string>#include<sstream>#include<algorithm>using namespace std;int cmp(string x,string y){    return x+y<y+x;}stringstream ss;int n,i,flag=0,x;char m[80008];string a[10001],t;int main(){    cin>>n;    for(i=0;i<n;i++) cin>>a[i];    sort(a,a+n,cmp);    for(i=0;i<n;i++) t=t+a[i];ss<<t;ss>>m;ss>>x;    if(n==1)    {        cout<<x<<endl;        return 0;    }    for(i=0;m[i];i++)    {        if(m[i]!='0') flag=1;        if(flag==1) cout<<m[i];    }    return 0;}

原创粉丝点击