第十二章 贪心 4 AcWing 1556. 月饼

野性酷女 2024-03-31 13:50 198阅读 0赞

第十二章 贪心 4 AcWing 1556. 月饼

原题链接

AcWing 1556. 月饼

算法标签

贪心

思路

优先选择性价比最高的月饼出售

证明

若优先选择性价非最高的月饼出售可以获取最大利润
将性价比非最高的月饼换为选择性价比最高的月饼出售,可以保证最大利润, 与原假设矛盾。

代码

  1. #pragma GCC optimize(2)
  2. #pragma GCC optimize(3)
  3. #include<bits/stdc++.h>
  4. #define int long long
  5. #define xx first
  6. #define yy second
  7. #define ump unordered_map
  8. #define us unordered_set
  9. #define pq priority_queue
  10. #define rep(i, a, b) for(int i=a;i<b;++i)
  11. #define Rep(i, a, b) for(int i=a;i>=b;--i)
  12. using namespace std;
  13. typedef pair<int, int> PII;
  14. const int N=1005, inf=0x3f3f3f3f3f3f3f3f, mod=1e9+7;
  15. const double Exp=1e-8;
  16. //int t, n, m, cnt, ans;
  17. double aw[N], av[N];
  18. struct Ca{
  19. double w, v;
  20. bool operator< (const Ca &c) const{
  21. return v/w>c.v/c.w;
  22. }
  23. }c[N];
  24. inline int rd(){
  25. int s=0,w=1;
  26. char ch=getchar();
  27. while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
  28. while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
  29. return s*w;
  30. }
  31. void put(int x) {
  32. if(x<0) putchar('-'),x=-x;
  33. if(x>=10) put(x/10);
  34. putchar(x%10^48);
  35. }
  36. signed main(){
  37. ios::sync_with_stdio(false);
  38. cin.tie(0);
  39. cout.tie(0);
  40. int n;
  41. double d;
  42. scanf("%lld %lf", &n, &d);
  43. rep(i, 0, n){
  44. scanf("%lf", &c[i].w);
  45. }
  46. rep(i, 0, n){
  47. scanf("%lf", &c[i].v);
  48. }
  49. sort(c, c+n);
  50. double res=0;
  51. rep(i, 0, n){
  52. double r=min(d, c[i].w);
  53. res+=c[i].v/c[i].w*r;
  54. d-=r;
  55. if(d<=0){
  56. break;
  57. }
  58. }
  59. printf("%.2lf", res);
  60. return 0;
  61. }

参考文献

AcWing 1556. 月饼(PAT甲级辅导课)y总视频讲解

原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,198人围观)

还没有评论,来说两句吧...

相关阅读