PAT乙级1023

94 阅读1分钟

image.png 一道简单贪心,甚至你都看不出他想贪心(大概。

大概思路就是用数组存储输出的数字,将数值小的数放在数组前面。因为0不能放在数字的最前方,所以数组第一位要放除0以外最小的数,就可以了。

//foreverking
//贪心
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
//1023 组个最小数 (20 分)
//给定数字0-9各若干个。你可以以任意顺序排列这些数字,但必须全部使用。目标是使得最后得到的数尽可能小(注意 0 不能做首位)
int array[10];//存各个数字个数
int s[50];//放答案
int cnt;

int main(){
    for(int i = 0; i  < 10; i++)
        cin >> array[i];//存放
    
    for(int i = 1; i < 10; i++){
        if(array[i] != 0){
            //找到第一个拥有个数不为0的数字作为开头输出,从1~9找,因为0不能开头
            s[cnt++] = i;
            break;
        }
    }
    
    for(int i = 0; i < array[0]; i++)
        s[cnt++] = 0;
    for(int i = 0; i < array[s[0]] - 1;i++)
        s[cnt++] = s[0];
        
    for(int i = s[0] + 1; i <= 9; i++)
        for(int j = 0; j < array[i]; j++)
            s[cnt++] = i;
    
    for(int i = 0;i < cnt ; i++)
        cout << s[i];
    return 0;
}

当然可以优化一下,不存储数字,每找到一个数字就将他输出,省空间。

//foreverking
//贪心
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int a[10], t;
    for (int i = 0; i < 10; i++)
        cin >> a[i];
    for (int i = 1; i < 10; i++)
    {
        if (a[i] != 0)
        {
            cout << i;
            t = i;
            break;
        }
    }
    for (int i = 0; i < a[0]; i++)
        cout << 0;
    for (int i = 0; i < a[t] - 1; i++)
        cout << t;
    for (int i = t + 1; i < 10; i++)
        for (int k = 0; k < a[i]; k++)
            cout << i;
    return 0;
}

题目链接