题目:
Problem Statement |
|||||||||||||
TopCoder admin mystic_tc is sitting in front of a table. He found N sealed boxes of candies on the table. He is not sure how many candies each box contains. However, he knows the following information:
You know that mystic_tc eats candies as follows: first he chooses a subset of the boxes, then he opens them and eats all the candies he found inside. He wants to eat at least X candies. And as he is smart, he will always choose a subset of boxes for which he is sure that they must contain at least X candies. You are given the ints C and X, and the vector <int>s low and high. Return the smallest number of boxes mystic_tc may choose. |
|||||||||||||
Definition |
|||||||||||||
|
|||||||||||||
Limits |
|||||||||||||
|
|||||||||||||
Constraints |
|||||||||||||
- | low and high will contain between 1 and 50 elements, inclusive. | ||||||||||||
- | low and high will contain the same number of elements. | ||||||||||||
- | Each element of low and high will be between 1 and 10,000,000, inclusive. | ||||||||||||
- | For each i, high[i] will be greater than or equal to low[i]. | ||||||||||||
- | C will be between the sum of all elements of low and the sum of all elements of high, inclusive. | ||||||||||||
- | X will be between 1 and C, inclusive. | ||||||||||||
Examples |
|||||||||||||
0) | |||||||||||||
|
|||||||||||||
1) | |||||||||||||
|
|||||||||||||
2) | |||||||||||||
|
|||||||||||||
3) | |||||||||||||
|
|||||||||||||
4) | |||||||||||||
|
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
分析:从1)这个例子来看,要看low数组,比如5,3两个加起来为8,说明至少有8,那么2个盒子即可。
从2)这个例子来看,要看high数组,比如8,12,8加起来来28,那么一共C=58,也就是说剩下的两个盒子至少有30.
故最终结果是从上面两个中取更小值。
代码:
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class MysticAndCandies { public: int minBoxes(int, int, vector <int>, vector <int>); }; int MysticAndCandies::minBoxes(int C, int X, vector <int> low, vector <int> high) { sort(low.begin(),low.end(),greater<int>()); int ret1 = 0; int sum1 = 0; for(int i=0;i<low.size();i++) { sum1+=low[i]; ret1++; if(sum1>=X) break; } int ret2 = 0; int sum2 = 0; sort(high.begin(),high.end()); for(int i=0;i<high.size();i++) { sum2+=high[i]; ret2++; if(sum2>=C-X) { if(sum2!=C-X) ret2--; break; } } return min(ret1,(int)low.size()-ret2); } //Powered by [KawigiEdit] 2.0!
原文:http://blog.csdn.net/wangyuquanliuli/article/details/18992427