贪心
题目链接:SDNUOJ1017
一开始,我以为这是一个类似于01背包的动态规划问题,结果仔细读题发现,这是一个贪心的入门题…
思路
贪心嘛,他只要求数量最多,又不是质量最大(质量最大的话请移步动态规划的背包问题),所以说
- 读入并存储所有苹果的重量
- 对苹果重量进行排序(使用sort)
- 从小到大往里装啊,使劲塞,哈哈哈哈哈,数量最多,先塞小的。
代码
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int a[2001];//苹果数据
int main()
{
ios::sync_with_stdio(false);//关闭输入输出流同步,提高cin速度
int m,n;
cin>>m>>n;
//苹果质量的读入和存储
for(int i=1;i<=n;i++){
cin>>a[i];
}
int ans=0;
int t=0;
//排序
sort(a+1,a+n+1);
int i=1;
while(t<=m&&i<=n){
t+=a[i];
i++;
ans++;
}
if(i==n+1) cout<<n<<endl;
else cout<<ans-1<<endl;
return 0;
}
其实我发现ans用不到,后期的i就直接表示答案就行,不过也不差这几个字节的内存,就懒得改啦,233333…