zoukankan      html  css  js  c++  java
  • HDU1106-排序

    题目链接:点击打开链接

    Problem Description

    输入一行数字,如果我们把这行数字中的‘5’都看成空格,那么就得到一行用空格分割的若干非负整数(可能有些整数以‘0’开头,这些头部的‘0’应该被忽略掉,除非这个整数就是由若干个‘0’组成的,这时这个整数就是0)。

    你的任务是:对这些分割得到的整数,依从小到大的顺序排序输出。
     

    Input

    输入包含多组测试用例,每组输入数据只有一行数字(数字之间没有空格),这行数字的长度不大于1000。  

    输入数据保证:分割得到的非负整数不会大于100000000;输入数据不可能全由‘5’组成。

    Output

    对于每个测试用例,输出分割得到的整数排序的结果,相邻的两个整数之间用一个空格分开,每组输出占一行。

    Sample Input

     

    0051231232050775

    Sample Output

     

    0 77 12312320

    思路:就是遍历字符串,处理。然后排序。虽然看着简单。但是情况比较多(处理temp有两种情况:①遇到了5,②到了结尾)还有就是涉及string 转化为 int 型,介绍几种互相转化的方法:①atoi(s.c_str()) 因为它的参数是char* 类型。《延伸,还有atof--浮点型,stol--long型》②用流sstream:

    示例代码:

    #include <string>
    #include <sstream>
    
    using namespace std;
    void main()
    {
        // int 转 string
        stringstream ss;
        int n = 123;
        string str;
        ss<<n;
        ss>>str;
        // string 转 int
        str = "456";
        n = atoi(str.c_str());
    }

    AC代码:

    #include<iostream>
    #include<queue>
    #include<algorithm>
    #include<stack>
    #include<string>
    #include<map>
    #include<set>
    #include<cstdio>
    #include<cstdlib>
    #include<cctype>
    #include<cstring>
    
    using namespace std;
    const int MAX = 10010;
    const int INF = 0X3f3f3f;
    
    string s, temp;
    
    vector<string> t;//存储分离的字符串
    vector<int> tt;//存储分离的整数
    
    int main() {
        while(cin >> s) {
            int len = s.length();
            for(int i = 0; s[i]; i++) {//遍历
                if(s[i] == '5') {处理temp的第一种情况
                    if(temp.size() != 0) {//防止有连续的5
                        t.push_back(temp);
                        temp.clear();//及时清除
                    }
                } else {
                    temp += s[i];
                    if(i+1 == len) {//处理temp的第二种情况
                        t.push_back(temp);
                        temp.clear();//及时清除
                    }
                }
            }
            for(int i = 0; i < t.size(); i++) {
                int x = atoi(t[i].c_str());//atoi的参数是需要 char* 类型, 所以转化。
                tt.push_back(x);
            }
            sort(tt.begin(), tt.end());
            for(int i = 0; i < tt.size(); i++) {
                if(i == 0)
                    cout << tt[i];
                else
                    cout << " " << tt[i];
            }
            t.clear();
            temp.clear();
            tt.clear();
            cout << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    vue自定义指令,自动调用下载的方法
    electron桌面通知,修改默认通知应用名electron.app.Electron为自己应用的名称
    C++二叉树前中后序遍历(递归&非递归)统一代码格式
    反转链表和反转链表2
    基于partition的递归
    C++归并排序(数组&链表)
    关于C++跨平台
    Visual Studio 2019社区版:错误 MSB6006 “CL.exe”已退出,代码为 2
    腾讯2017校招开发工程师笔试试卷(一)答题解析
    C++面试高频题
  • 原文地址:https://www.cnblogs.com/ACMerszl/p/9572988.html
Copyright © 2011-2022 走看看