PAT乙級.1023. 組個最小數 (20)

1023. 組個最小數 (20)


題目

給定數字0-9各若干個。你可以以任意順序排列這些數字,但必須全部使用。目標是使得最後得到的數儘可能小(注意0不能做首位)。例如:給定兩個0,兩個1,三個5,一個8,我們得到的最小的數就是10015558。

現給定數字,請編寫程序輸出能夠組成的最小的數。

輸入格式

每個輸入包含1個測試用例。每個測試用例在一行中給出10個非負整數,順序表示我們擁有數字0、數字1、……數字9的個數。整數間用一個空格分隔。10個數字的總個數不超過50,且至少擁有1個非0的數字。

輸出格式

在一行中輸出能夠組成的最小的數。

輸入樣例

2 2 0 0 0 3 0 0 1 0

輸出樣例

10015558

PAT鏈接


思路

散列表存每個數字出現次數

int hashTable[10];

找到第一個不是0的數當最高位
從0開始由低到高,當hashTable[i]不爲0時候,輸出i


代碼

version1.0(需要額外統計總位數,不過似乎快點,不一定要全部遍歷)

/**
* @tag     PAT_B_1023
* @authors R11happy ([email protected])
* @date    2016-9-4 20:59-21:19
* @version 1.0
* @Language C++
* @Ranking  690/686
* @function null
*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

int hashTable[10];

int main(int argc, char const *argv[])
{
    int cnt = 0;
    for(int i = 0; i<10; i++)
    {
        scanf("%d", &hashTable[i]);
        if(hashTable[i])    cnt += hashTable[i];
    }
    //從1開始找出第一個非0數輸出
    for(int i = 1; i<10; i++)
    {
        if(hashTable[i])
        {
            printf("%d",i );
            hashTable[i]--;     //輸出一個數,對應hashTable要記得減1
            break;
        }
    }
    cnt++;
    for(int i = 0; cnt > 0 && i<10 ; i++)
    {
        while(hashTable[i] > 0) //不能用if
        {
            printf("%d",i );
            cnt--;
            hashTable[i]--;     //輸出一個數,對應hashTable要記得減1
        }
    }
    return 0;
}

version2.0(寫法比較簡單)

/**
* @tag     PAT_B_1023
* @authors R11happy ([email protected])
* @date    2016-9-4 20:59-
* @version 1.0
* @Language C++
* @Ranking  null
* @function null
*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

int hashTable[10];

int main(int argc, char const *argv[])
{
    for (int i = 0; i<10; i++)
    {
        scanf("%d", &hashTable[i]);
    }
    for (int i = 1; i<10; i++)
    {
        if (hashTable[i])
        {
            printf("%d", i);
            hashTable[i]--;
            break;
        }
    }
    for(int i = 0; i < 10; i++)
    {
        for (int j = 0; j < hashTable[i]; j++)
        {
            printf("%d", i);
        }
    }
    return 0;
}

收穫

雙重for循環可以考慮用for+while代替,可提前結束,注意下面代碼:

    for(int i = 0; cnt > 0 && i<10 ; i++)
    {
        while(hashTable[i] > 0) //不能用if
        {
            printf("%d",i );
            cnt--;
            hashTable[i]--;     //輸出一個數,對應hashTable要記得減1
        }
    }

其中的while千萬不能用if代替,因爲同一個i可能重複輸出多次。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章