1038. Recover the Smallest Number (30)

1.题目是把一些数,通过组合,变成一个最小的数(在这些数的所有组合中最小)

2.使用贪心算法,贪心标准为:

1)如果两个数中,数a是数b的前缀,或者数b是数a的前缀,那么判断字符串相加后a+b与b+a的大小,进行确定前后顺序

2)如果不是上面1)中的两种情况,直接按照string进行大小比较

3.该题目可以通过微小的修改,改为求最大的数。

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

 
AC代码:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory.h>
#include "limits.h"
using namespace std;

bool cmp(const string&a,const string&b)
{
    //如果a和b,是前缀关系是,要比较a+b与b+a的大小
    if(a.size()<b.size()&&a==b.substr(0,a.size()))
        return a+b<b+a;
    else if(b.size()<a.size() && b==a.substr(0,b.size()))
        return a+b<b+a;
    else return a<b;
}
/*
 5 32 321 3214 0229 87
 4 11 122 12 10
 4  122 12 10 11
 */

int main(void)
{
    int n;
    cin>>n;
    vector<string> str(n);
    for(int i=0;i<n;i++)
    {
        cin>>str[i];
    }
    sort(str.begin(), str.end(),cmp);
    string ans="";
    for(int i=0;i<n;i++)
    {
        ans+=str[i];
    }
    int i=0;
    while(ans[i] == '0')
    {
        i++;
    }
    //注意全为0的状态
    if(ans.substr(i)=="") cout<<0<<endl;
    else cout<<ans.substr(i)<<endl;
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注