一二三四五 上山打老虎

PAT (Basic Level) Practice1020 -月饼 (25分)

题目链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805301562163200

题意:给定n组月饼的库存量和总价,以及要采购的月饼数量,求采购需要的最少money

思路:简单贪心,按照单价降序排序后切割选取

坑点:题目中仅说明 库存量和总售价 是正数 并未说明是正整数 ,当作正整数会有个测试点过不去

反思对于计算或者涉及到小数的题目最好都定义为double来使用

#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
    double  num,p;
}a[1005];
bool cmp(struct node s,struct node t){
    return s.p*t.num>s.num*t.p;
}
int main (){
    int n;
    double m;
    scanf("%d%lf",&n,&m);
    for(int i=0;i<n;i++){
        scanf("%lf",&a[i].num);
    }
    for(int i=0;i<n;i++){
        scanf("%lf",&a[i].p);
    }
    sort(a,a+n,cmp);
    double ans=0;
    for(int i=0;i<n;i++){
        if(a[i].num<m){
            m-=a[i].num;
            ans+=a[i].p;
        }
        else{
            ans+=1.0*m*a[i].p/a[i].num;
            break;
        }
    }
    printf("%.2f",ans);
    return 0;
}
posted @ 2021-01-20 10:42  黒川川  阅读(68)  评论(0)    收藏  举报