PATL2_003 月饼 贪心法

思路:现将月饼以单价从大到小排序,如果能将一种月饼全取就全取 不能全取就取一部分

样例:

3 20
18 15 10
75 72 45

排完序后 

库存 总价值 单价

15      72      4.8

10      45      4.5

 18    75       4.17

一共要去20万吨

初始化 总价值=0

第一次取20万吨 取第一种月饼 能全取 总价值+=72

第二次取20-15=5万吨 取第二种月饼 不能全取 总价值+=(5*4.5)= 94.5 循环结束

代码如下:

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct Yb{
    double weight;
    double price;
    double dj;
}s[1001];
bool comp(Yb a, Yb b){
    return a.dj>b.dj;
}
int main()
{
    int n,need;
    double weight,price;
    cin>>n>>need;
    for(int i=0;i<n;i++){
        cin>>weight;
        s[i].weight = weight;
    }
    for(int i=0;i<n;i++){
        cin>>price;
        s[i].price = price;
        s[i].dj = s[i].price/s[i].weight;
    }
    sort(s,s+n,comp);
    double sumPrice=0;
    for(int i=0;i<n;i++){
        if(need>s[i].weight){
            need -= s[i].weight;
            sumPrice += s[i].price;
        } else {
            sumPrice += s[i].dj * need;
            break;
        }
    }
    printf("%.2lf\n",sumPrice);    
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/xiaoguapi99/article/details/86761255
今日推荐