[关闭]
@Moritz 2019-03-29T08:13:12.000000Z 字数 1355 阅读 423

L2-00 月饼

unsolved PTA C++ 贪心 所有文稿

关键词:贪心,比较函数的运用

一个非常重要的点:比较函数 (注意,必须用><,不可出现=sort是不稳定排序)

  1. /*22:45-23:00 部分错误*/
  2. /*有一个测试用例段错误 没找出来bug*/
  3. #include <iostream>
  4. #include <cmath>
  5. #include <algorithm>
  6. #include <iostream>
  7. using namespace std;
  8. const int maxn=1010;
  9. struct Item{
  10. double kc,w;
  11. double d;
  12. };//a[maxn];
  13. bool cmpare(Item a,Item b){ //const必须加,不然会错,目前不懂为啥。当return的是ture时,a先输出,所以示例中是升序
  14. return a.d > b.d;
  15. }
  16. int main(){
  17. int n,d;
  18. cin>>n>>d;
  19. Item* a=new Item[n];
  20. for(int i=0;i<n;i++) cin>>a[i].kc;
  21. for(int i=0;i<n;i++){
  22. cin>>a[i].w;
  23. a[i].d=a[i].w*1.0/a[i].kc;
  24. }
  25. sort(a, a+ n,cmpare);
  26. //for(int i=0;i<n;i++) cout<<a[i].d<<endl;
  27. double tot=0.0;
  28. int now=0;
  29. while(1){
  30. if(a[now].kc<d){
  31. d-=a[now].kc;
  32. tot+=a[now].w;
  33. now++;
  34. }
  35. else{
  36. tot+=a[now].d*1.0*d;
  37. break;
  38. }
  39. }
  40. printf("%.2f",tot);
  41. system("pause");
  42. return 0;
  43. }

以下是完全AC的程序,暂时没发现哪儿不同

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. using namespace std;
  5. struct Bean{
  6. double number; //销售量
  7. double price; //售价
  8. double unitPrice; //单价
  9. };
  10. //排序比较函数
  11. int compare(Bean a,Bean b){
  12. return a.unitPrice > b.unitPrice;
  13. }
  14. int main(){
  15. int n,i,j;
  16. double needs;
  17. cin>>n>>needs;
  18. Bean* beans=new Bean[n];
  19. for(i=0;i<n;i++){
  20. cin>>beans[i].number;
  21. }
  22. for(i=0;i<n;i++){
  23. cin>>beans[i].price;
  24. beans[i].unitPrice=beans[i].price/beans[i].number;
  25. }
  26. sort(beans,beans+n,compare); //按单价降序
  27. double revenue=0;
  28. for(i=0;i<n;i++){
  29. if(needs<=beans[i].number){
  30. revenue+=beans[i].unitPrice*needs;
  31. break;
  32. }else{
  33. revenue+=beans[i].price;
  34. needs-=beans[i].number;
  35. }
  36. }
  37. printf("%.2lf\n",revenue);
  38. }

2019.3.16

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注