P1012 拼數(shù)

1、思路

按位排序,第一位優(yōu)先級大于第二位,第一位相同接著比第二位。照這樣寫完會發(fā)現(xiàn)有一組輸入輸出存在問題。比較321與32,正常的比較得到的結(jié)果是321>32,但是顯然32321>32132。改進(jìn)措施是將輸入數(shù)據(jù)的首位先壓入另一個數(shù)的棧中,即就是比較了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、改進(jìn)

使用string比較

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容