NYOJ-791 Color the fence (来源CodeForce)

版权声明:Copyright : 李三金,原创文章转载标明出处即可。 https://blog.csdn.net/santa9527/article/details/53312338

NYOJ-791 Color the fence (贪心)

Color the fence
时间限制:1000 ms | 内存限制:65535 KB
难度:2

描述

Tom has fallen in love with Mary. Now Tom wants to show his love and write a number on the fence opposite to 

Mary’s house. Tom thinks that the larger the numbers is, the more chance to win Mary’s heart he has.

Unfortunately, Tom could only get V liters paint. He did the math and concluded that digit i requires ai liters paint. 

Besides,Tom heard that Mary doesn’t like zero.That’s why Tom won’t use them in his number.

Help Tom find the maximum number he can write on the fence.

输入
There are multiple test cases.
Each case the first line contains a nonnegative integer V(0≤V≤10^6).
The second line contains nine positive integers a1,a2,……,a9(1≤ai≤10^5).
输出
Printf the maximum number Tom can write on the fence. If he has too little paint for any digit, print -1.
样例输入

5
5 4 3 2 1 2 3 4 5
2
9 11 1 12 5 8 9 10 6

样例输出

55555
33

来源
CodeForce
上传者
TC_李远航

来源于CodeForce的题目,其实并不难。裸裸的贪心题,可是总是想不通如何用代码实现。

题目很简单,给你v体积油漆,再给你1~9数字分别消耗多少油漆,输出能画出的最大数字。

很明显,我们只要让数字尽量长就可以,数字越长越大嘛,但是,在保证长度的同时,我们也要让高位数字尽量大(贪心策略)。易知,v除以消耗最少的油漆可以得知我们能画的最长数字的长度,然而最长不仅仅可以由最少数字得到。比如:v=5 a={22,30,2,3,31,14,15,7,9} 最长长度为2,且消耗最少的数字组成结果为33,可最优结果为43。所以只要我们能保证我们得到的是高位数字比选择消耗最少的数所得高位数字大并且位数相等的数即可。

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#define MAXN 1111101
using namespace std;
int cost[MAXN];
int main()
{
    int v;
    int i,j,k;
    while(~scanf("%d",&v))
    {
        int minn=MAXN;
        for(i=1; i<=9; i++)
        {
            scanf("%d",&cost[i]);
            if(cost[i]<minn)
                minn=cost[i];
        }
        if(minn>v)//油漆太少的情况
        {
            printf("-1\n");
            continue;
        }
        for(i=v/minn; i>=1; i--)//目前的染料如果染最小花费那个数字可以染多少位
            for(j=9; j>=1; j--) //从大到小遍历数字
                if(v>=cost[j]&&(v-cost[j])/minn+1>=i)
                   //目前的染料能染较大的数字且保证跟染最小那个数字可染的位数相同
        {
            printf("%d",j);//贪心选择染大的数字
            v-=cost[j];
            break;
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/santa9527/article/details/53312338
今日推荐