前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【PAT甲级】Recover the Smallest Number

【PAT甲级】Recover the Smallest Number

作者头像
喜欢ctrl的cxk
发布2019-11-08 14:51:39
3270
发布2019-11-08 14:51:39
举报
文章被收录于专栏:Don的成长史Don的成长史

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_42449444/article/details/89716717

Problem Description:

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 (≤10​4​​) 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. Notice that the first digit must not be zero.

Sample Input:

代码语言:javascript
复制
5 32 321 3214 0229 87

Sample Output:

代码语言:javascript
复制
22932132143287

解题思路:

建立一个vector用来存放string型的数字,自定义一个比较规则cmp来使数字构成的字符串经可能小,然后以cmp为比较规则来对vector进行sort。接着判断字符串是不是以0开头,若字符串以0开头则需要删除0。然后判断字符串是不是为空(即字符串长度是否为0),若字符串str为空,则令str = "0",最后输出str即可。

AC代码:

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;

bool cmp(string s1,string s2)   //使数字构成的字符串要尽可能小
{
    return s1+s2 < s2+s1;
}

int main()
{
    int N;
    cin >> N;
    vector<string> v;
    for(int i = 0; i < N; i++)
    {
        string temp;
        cin >> temp;
        v.push_back(temp);
    }
    sort(v.begin(), v.end(),cmp);
    string str = "";
    for(auto it : v)
    {
        str += it;
    }
    int len = str.length();
    while(len !=0 & str[0] == '0')   //一大串数字组成的字符串第一个数字不能为0
    {
        str.erase(str.begin());
    }
    if(len == 0)
    {
        str = "0";
    }
    cout << str << endl;
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem Description:
  • Input Specification:
  • Output Specification:
  • Sample Input:
  • Sample Output:
  • 解题思路:
  • AC代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档