• 1038 Recover the Smallest Number (30分)(贪心)


    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 (≤) 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:

    5 32 321 3214 0229 87
    

    Sample Output:

    22932132143287

    题目分析:贪心算法 没想明白 贪心算法利用局部最优而达到整个问题的最优解
    所以在compare中写的比较函数是 a+b与b+a进行比较
     1 #define _CRT_SECURE_NO_WARNINGS
     2 #include <climits>
     3 #include<iostream>
     4 #include<vector>
     5 #include<queue>
     6 #include<map>
     7 #include<stack>
     8 #include<algorithm>
     9 #include<string>
    10 #include<cmath>
    11 using namespace std;
    12 bool compare(const string& a, const string& b)
    13 {
    14     return a + b < b + a;
    15 }
    16 int main()
    17 {
    18     vector<string> S;
    19     int N;
    20     cin >> N;
    21     string s;
    22     for (int i = 0; i < N; i++)
    23     {
    24         cin >> s;
    25         S.push_back(s);
    26     }
    27     s = "";
    28     sort(S.begin(), S.end(), compare);
    29     for (auto it : S)
    30         s += it;
    31     while (s.length() && s.at(0) == '0')
    32         s.erase(s.begin());
    33     if (!s.length())cout << 0;
    34     else
    35         cout << s;
    36 }
    View Code
  • 相关阅读:
    Javascript异步编程的4种方法
    同步编程和异步编程
    关于js 异步回调的一些方法
    array的方法 没记住的
    阮一峰关于reduce 和transduce的博客
    CSS开发小技巧
    提升自己的一个网址
    asm.js 和 Emscripten 入门教程
    Koa -- 基于 Node.js 平台的下一代 web 开发框架
    C#中使用handsonetable的一个例子
  • 原文地址:https://www.cnblogs.com/57one/p/12017997.html
Copyright © 2020-2023  润新知