题目
思路
贪心算法:依次取单价从高到低商品
易错点
题目中库存量和需求量只说明是正数,未说明是正整数,所以可能是double类型,若用int,有一个测试点错误
题解
#include <iostream>
#include <vector>
#include <cstring>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1010;
struct Product{
double w;//w是库存
double p;//p是单价
double c;//c是每种总价
};
vector<Product> pds;
bool cmp(Product p1,Product p2){
return p1.p>p2.p;
}
int main(int argc,char * argv[]) {
double n,t; // n样品种类数,t市场总需求量
double all; // all总利润
scanf("%lf%lf",&n,&t);
for(int i=0; i<n; i++) {
Product p;
scanf("%lf",&p.w);
pds.push_back(p);
}
for(int i=0; i<n; i++) {
scanf("%lf",&pds[i].c);
pds[i].p=pds[i].c/pds[i].w;
}
sort(pds.begin(),pds.end(),cmp);
for(int i=0; i<n&&t>0; i++) {
if(t>=pds[i].w) {
all+=pds[i].c;
t-=pds[i].w;
} else {
all+=(t*pds[i].p);
t=0;
}
}
printf("%0.2f",all);
return 0;
}