• A1038. Recover the Smallest Number


    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

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<string>
     4 #include<algorithm>
     5 using namespace std;
     6 string str[10001], ans;
     7 bool cmp(string a, string b){
     8         return a + b < b + a;
     9 }
    10 int main(){
    11     int N, index = -1;
    12     scanf("%d", &N);
    13     for(int i = 0; i < N; i++)
    14         cin >> str[i];
    15     sort(str, str + N, cmp);
    16     for(int i = 0; i < N; i++){
    17         ans += str[i];
    18     }
    19     int i = 0;
    20     while(ans[i] != '' && ans[i] == '0'){
    21         index = i;
    22         i++;
    23     }
    24     if(index != -1)
    25         ans.erase(0, index + 1);
    26     if(ans.length() == 0)
    27         cout << "0";
    28     else cout << ans;
    29     cin >> N;
    30     return 0;
    31 }
    View Code

    总结:

    1、题意:将若干字符串拼接起来,使得组成的数字最小。如果直接按照字典序由小到大排列再拼接是不对的。正确做法:比较串a和串b的位置关系时应考虑,如果a+b < b + a,则说明a前b后所组成的数字更小。

    2、输出结果要去掉前导0,但不能仅仅对str[0]去0,因为有可能存在str[N] = {"0000", "0000", "0000"}的情况,应全部拼接起来后统一去除0,当最终得到的字串长度为0时,需要人为输出一个0。

    3、string去除子串:str.erase(首位置, 长度)

  • 相关阅读:
    JDBC性能优化点
    56992 vuser_init.c(12): Error: Socket descriptor not found.
    ubuntu用apt安装apache2时,出现E:未发现软件包 apache2
    loadrunner --global schedule设置
    loadrunner ---模拟多IP登录
    Loadrunner ---集合点设置
    LoadRunner --HTML/URL录制方式的选择规则
    LoadRunner ---参数化数据源(oracle,mssql,excel)
    LoadRunner ---协议分析
    LoadRunner ---思考时间设置
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8503463.html
Copyright © 2020-2023  润新知