题目链接
题目详情
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≤ i ≤ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.
Input The first line contains exactly one integer k (0 ≤ k ≤ 100). The next line contains twelve space-separated integers: the i-th (1 ≤ i ≤ 12) number in the line represents .
Output Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.
题目大意及解题思路
大意:
今天,佩蒂亚打开橱柜,发现里面有一张可怕的纸条,他的父母给他留下了责任:他应该全年每天早上、下午和晚上给他们最喜欢的花浇水。“等一下!”——佩蒂亚想。他知道一个事实,如果他在第i节完成了父母的任务 一年中的一个月,花会长出厘米,如果他在第i个月不给花浇水,那么这个月花就不会长了。Petya也知道,尽管他尽了最大努力,但如果花朵的生长量严格低于k厘米,他的父母不会相信他一直在给它浇水。帮助Petya选择浇水的最小月数,因为花朵的生长应不低于k厘米。如果花一年不能长k厘米,请打印-1。
解题思路:
首先我们将数组排序,然后从后往前枚举最大的值并累加,同时计数器++,当和超过k时,我们就可以跳出循环,然后判断一下和是否小于k(小于计数器=-1),并输出计数器的值。
AC代码
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int k,a[12];
cin >> k;
for (int i = 0; i < 12; i++) cin >> a[i];
sort(a, a + 12);
int cnt = 0, sum = 0;
for (int i = 11; i >= 0; i--)
{
if (sum >= k) break;
else
{
sum += a[i];
cnt++;
}
}
if (sum < k) cnt = -1;
cout << cnt;
return 0;
}