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
思路:先考虑几种极端情况,将极端情况分离出去,极端情况如下,先找出花费油漆数目最少的数字,
1:如果这个花费油漆最少的数字花费的油漆比总油漆大说明一个数字也刷不了直接输出-1.
2:当总油漆数除以花费油漆做少的数字的花费的油漆数能整除时,那么最优的情况一定输出一堆都是这个数字的数字
3:当所有特殊情况都考虑过后,此时就是挨个选择了,这里用cnt=v/minx(最多能刷cnt份数字)作为外层循环次数
然后在内层按照从9到1(贪心策略)进行挨个选择,如果当前数字花费油a[j]<=v 且(v-a[j])/minx >= i.那么就把这个数字刷上,同时总油漆减去这个数字的花费。跳出内层循环。
AC代码:
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std ; int a[10] ; double b[10] ; int v ; int main() { while(scanf("%d",&v)!=EOF) { int minx = 1e9 ; int k = 0 ; for(int i = 1 ;i<=9 ;i++) { scanf("%d",&a[i]) ; if(a[i] <= minx) { minx = a[i] ; k = i ; } } if(v < minx) //最小花费的数字都没法画 { printf("-1\n") ; continue ; } int cnt = v/minx ; for(int i = cnt-1 ;i>=0 ;i--) //最多能画cnt个数字 { for(int j = 9 ;j>=1 ;j--) { if(v-a[j]>=0 && (v-a[j])/minx >= i) { v -= a[j] ; printf("%d",j) ; break ; } } } printf("\n") ; } return 0 ; }