贪心 --- 模板题
FatMouse' Trade#
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 41006 Accepted Submission(s): 13575
Problem Description
FatMouse
prepared M pounds of cat food, ready to trade with the cats guarding
the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input
The
input consists of multiple test cases. Each test case begins with a
line containing two non-negative integers M and N. Then N lines follow,
each contains two non-negative integers J[i] and F[i] respectively. The
last test case is followed by two -1's. All integers are not greater
than 1000.
Output
For
each test case, print in a single line a real number accurate up to 3
decimal places, which is the maximum amount of JavaBeans that FatMouse
can obtain.
Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.500
【题目来源】
【题目大意】
jack有M磅猫食,他想用这些猫食来换他最喜爱的javabeans,在他面前有n个房间,每个房间上表明了:J颗豆可以用F磅猫食来换取。
让你选择最优的方案换取最多的豆。
【题目分析】
贪心的水题,先排序,然后就按顺序选,直至将所有的猫食都换光。
#include<stdio.h> #include<algorithm> using namespace std; struct Node { int a,b; double c; }; Node node[1010]; bool cmp(Node a,Node b) { return a.c>b.c; } int main() { int n,m; while(scanf("%d%d",&n,&m),n!=-1&&m!=-1) { for(int i=0;i<m;i++) { scanf("%d%d",&node[i].a,&node[i].b); node[i].c=(double)node[i].a/(double)node[i].b; } sort(node,node+m,cmp); double sum=0; for(int i=0;i<m;i++) { if(n<=0) break; else { if(n>node[i].b) { sum+=node[i].a; n-=node[i].b; } else { sum+=n*node[i].c; break; } } } printf("%.3lf\n",sum); } return 0; }
作者:北岛知寒
出处:https://www.cnblogs.com/crazyacking/p/3753688.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?