PAT BASIC 1020 月饼

本文介绍了一个关于购物问题的贪心算法实现,通过单价排序选择单价最高的商品进行购买,直至预算耗尽。文章提供了完整的C++代码实现,并详细解释了排序和购买过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

本题考察了贪心的思想,不买对的,就买贵的。

先按照单价进行排序,在德才论中,我们已经会用qsort来给struct类型排序了,那么就用起来。

注意这里的库存量也是double类型的,不要被样例欺骗了。


代码:

#include<iostream>
#include<cstdlib>
#include<iomanip>
using namespace std;
struct Objc
{
  double num;
  double total;
  double upr;
}th[1002];
int n;
double d;
int cmp(const void *a, const void *b)
{
  struct Objc *aa = (Objc *)a;
  struct Objc *bb = (Objc *)b;
  if (aa->upr < bb->upr)
    return 1;
  else return -1;
}

int main()
{
  int i;
  int count = 0;
  double ans = 0;
  cin >> n >> d;
  for (i = 0; i < n; i++)
    cin >> th[i].num;
  for (i = 0; i < n; i++)
  {
    cin >> th[i].total;
    th[i].upr = th[i].total / th[i].num;
  }
  qsort(th, n, sizeof(th[0]), cmp);
  while (d > 0 && count < n)
  {
    if (th[count].num > d)
    {
      ans = ans + d*th[count].upr;
      d = 0;
      continue;
    }
    ans += th[count].total;
    d -= th[count].num;
    count++;
  }
  cout.setf(ios::fixed);
  cout << fixed << setprecision(2) << ans << endl;
  //while (1)
  //{
  //}
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值