美文网首页
P1012 拼数

P1012 拼数

作者: 张的笔记本 | 来源:发表于2020-03-02 13:19 被阅读0次

    1、思路

    按位排序,第一位优先级大于第二位,第一位相同接着比第二位。照这样写完会发现有一组输入输出存在问题。比较321与32,正常的比较得到的结果是321>32,但是显然32321>32132。改进措施是将输入数据的首位先压入另一个数的栈中,即就是比较了323与3213的大小。

    1、代码

    #include<iostream>
    #include<stack>
    #include<algorithm>
    using namespace std;
    bool cmp(int a, int b){
        stack<int> temp2, temp3;
        int aa = a, bb = b;
        while(aa > 9) aa = aa / 10;
        while(bb > 9) bb = bb / 10;
        temp2.push(bb);//放入哨兵
        temp3.push(aa);
        while(a != 0){
            temp2.push(a % 10);
            a = a / 10;
        }
        while(b != 0){
            temp3.push(b % 10);
            b = b / 10;
        }
        while(!temp2.empty() && !temp3.empty()){
            if(temp2.top() > temp3.top())
                return true;
            else if(temp2.top() < temp3.top())
                return false;
            temp2.pop();//这个pop返回void
            temp3.pop();
        }
        return true;//两个元素相等,随便将哪一个放到前面
    }
    int main(){
        int n, i;
        cin>>n;
        int *a = new int[n];
        for(i = 0; i < n; ++i)
            cin>>a[i];
        sort(a, a + n, cmp);
        for(i = 0; i < n; ++i)
            cout<<a[i];
        delete []a;
        return 0;
    }
    

    3、改进

    使用string比较

    相关文章

      网友评论

          本文标题:P1012 拼数

          本文链接:https://www.haomeiwen.com/subject/yiymkhtx.html