题目来源:http://noi.openjudge.cn/ch0406/2407/
2407:书架
总时间限制: 20000ms 单个测试点时间限制: 1000ms 内存限制: 65536kB
描述
John最近买了一个书架用来存放奶牛养殖书籍,但书架很快被存满了,只剩最顶层有空余。
John共有N头奶牛(1≤ N ≤ 20,000),每头奶牛有自己的高度Hi(1≤ Hi ≤ 10,000),N头奶牛的总高度为S。书架高度为B(1≤ B ≤ S < 2,000,000,007).
为了到达书架顶层,奶牛可以踩着其他奶牛的背,像叠罗汉一样,直到他们的总高度不低于书架高度。当然若奶牛越多则危险性越大。为了帮助John到达书架顶层,找出使用奶牛数目最少的解决方案吧。
输入
第1行:空格隔开的整数N和B
第2~N+1行:第i+1行为整数Hi
输出
能达到书架高度所使用奶牛的最少数目
样例输入
6 40
6
18
11
13
19
11
样例输出
3
-----------------------------------------------------
思路
贪心水题。
-----------------------------------------------------
代码
#include<iostream> #include<fstream> #include<algorithm> using namespace std; const int NMAX = 20005; int H[NMAX] = {}; int main() { #ifndef ONLINE_JUDGE ifstream fin ("0406_2407.txt"); int n,b,i,cnt = 0; fin >> n >> b; for (i=0; i<n; i++) { fin >> H[i]; } fin.close(); sort(H, H+n); i = n-1; while (b>0) { b -= H[i]; cnt++; i--; } cout << cnt; return 0; #endif #ifdef ONLINE_JUDGE int n,b,i,cnt = 0; cin >> n >> b; for (i=0; i<n; i++) { cin >> H[i]; } sort(H, H+n); i = n-1; while (b>0) { b -= H[i]; cnt++; i--; } cout << cnt; #endif }