P1012 拼数

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比较

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容