Candy Distribution Again
There are N children, numbered 1,2,…,N.
Snuke has decided to distribute x sweets among them. He needs to give out all the xsweets, but some of the children may get zero sweets.
For each i (1≤i≤N), Child i will be happy if he/she gets exactly ai sweets. Snuke is trying to maximize the number of happy children by optimally distributing the sweets. Find the maximum possible number of happy children.
Constraints
- All values in input are integers.
- 2≤N≤100
- 1≤x≤109
- 1≤ai≤109
Input
Input is given from Standard Input in the following format:
N x a1 a2 … aN
Output
Print the maximum possible number of happy children.
Sample Input 1
3 70 20 30 10
Sample Output 1
2
One optimal way to distribute sweets is (20,30,20).
Sample Input 2
3 10 20 30 10
Sample Output 2
1
The optimal way to distribute sweets is (0,0,10).
Sample Input 3
4 1111 1 10 100 1000
Sample Output 3
4
The optimal way to distribute sweets is (1,10,100,1000).
Sample Input 4
2 10 20 20
Sample Output 4
0
No children will be happy, no matter how the sweets are distributed.
分析:從小到大喀什分糖,這樣就能確保得到準確糖的人數最多。
#include<iostream> #include<algorithm> using namespace std; int main() { long long n,x,a[105]; cin>>n>>x; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); int k=0; while(x>=a[k]){ x=x-a[k]; k++; if(k==n){ if(x==0) break; else {k--;break;} } } cout<<k<<endl; return 0; }