【机试练习】【C++】【PAT】B1020 月饼

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Xiblade/article/details/82377898
# include<cstdio>
# include<vector>
# include<algorithm>

using namespace std;

class Mooncake{

    private:
        double singlePrice = -1.0;
        double store = -1.0;
        double totalPrice = -1.0;

    public:
        Mooncake(double store, double totalPrice){
            this->store = store;
            this->totalPrice = totalPrice;
            this->singlePrice = totalPrice / store;
        }

        double getSinglePrice(){
            return this->singlePrice;
        }

        double getStore(){
            return this->store;
        }

        double getTotalPrice(){
            return this -> totalPrice;
        }

        double sell(double sellStore){
            if(this->store > 0 && this->store >= sellStore){
                this->store -= sellStore;
                this->totalPrice -= this->singlePrice * sellStore;  
                return this->singlePrice * sellStore;
            }
            else{
                this->store = -1.0;
                return totalPrice;
            }
        }
};
// 按照单价排列,单价高的放在前面 
bool cmp(Mooncake a, Mooncake b){
    return a.getSinglePrice() > b.getSinglePrice();
}

double tmp[1010] = {0};
int main(){
    vector<Mooncake> totalCake;
    //int N = 0, D = 0;
    int N = 0;
    double D = 0;
    scanf("%d %lf", &N, &D);
    // 暂存N个库存量 
    for(int i = 0 ; i < N; i++){
        scanf("%lf", &tmp[i]);
    }
    // 输入N个总价的同时生成月饼
    for(int i = 0; i < N; i++){
        double totalPrice;
        scanf("%lf", &totalPrice);
        Mooncake mk = Mooncake(tmp[i], totalPrice);
        totalCake.push_back(mk);    
    } 


    sort(totalCake.begin(), totalCake.end(), cmp);
    // cmp不能放在Mooncake里面
    // 然后以Mooncake.cmp传递函数 
    //这不太符合面向对象准则 

    double total = 0.000;

    // 这一个思路有一个测试用例过不了 
//  while(D > 0){
//      Mooncake currentCake = totalCake[0];  // 经过排序,已经确定了这是单价最高 
//      if(currentCake.getStore() > D){
//          total += currentCake.sell(D);
//          break; // 满足了所有市场需求 
//      }
//      else{
//          // 优先销售完售价最高的月饼
//          D -= currentCake.getStore();
//          total += currentCake.sell(currentCake.getStore());
//          totalCake.erase(totalCake.begin());
//      }
//  }

    // 遍历月饼的思路可以行得通 
    for(int i = 0; i < totalCake.size(); i++){
        Mooncake currentCake = totalCake[i];
        if(currentCake.getStore() <= D){
            D -= currentCake.getStore();
            total += currentCake.getTotalPrice(); //这个位置没体现出Sell 
        }   
        else{
            total += currentCake.sell(D);
            break;
        }
    }
    printf("%.2f",total);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Xiblade/article/details/82377898