于衡的布偶
Description 众所周知,于衡喜欢毛茸茸的东西,于是决定在双十一疯狂购物。已知双十一当天共有n个毛茸茸的布偶在售卖,价格分别为a1,a2……an。于衡只有m元钱,但他是个贪心的孩子,他想在不超出预算的情况下买到最多的布偶,请问于衡能最多买到多少布偶,输出买到的布偶数和剩下的可以用来吃土的钱。
Input 第一行:两个整数n和m;(n<=50,m<=10000)第二行:n个整数,每个玩具的花费a1,a2……an(价格为不超过1000的整数) Output 两个整数:1.能买到的布偶个数2.剩余的金钱
Sample Input 1 Sample Out
5 30 4 7
2 18 5 7 9
Sample Input 2 Sample Output2
3 88 2 59
22 7 67
思路:
关键点在于“不超出预算的情况下买到最多的布偶”,所以我们需要将输入的玩偶的价格进行升序排序,之后再进行计算,排序需要一个子函数或一个sort函数。【sort:包含与头文件algorithm中的排序函数,默认为升序排序】
源代码
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n,m,a[55],sum=0;
int i,j;
cin>>n>>m;
for( i=1;i<=n;i++)
{
cin>>a[i];
}
sort(a,a+i); //排序
for( j=0;j<n;j++)
{
sum=sum+a[j+1];
if(sum>=m)
break;
}
cout<<j<<" "<<m-sum+a[j+1]<<endl;
return 0;
}