貪心:spa
#include <cstdion> #include <algorithm> using namespace std; struct mooncake{ double store; //庫存量 double sell; //總售價 double price; //單價 }cake[1010]; bool cmp(mooncake a,mooncake b){ //按單價從高到低排序 return a.price>b.price; } int main(){ int n; double D; scanf("%d%lf",%n,%D); for(int i=0;i<n;i++){ scanf("%lf",&cake[i].store); } for(int i=0;i<n;i++){ scanf("%lf",&cake[i].sell); cake[i].price=cake[i].sell/cake[i].store; //計算單價 } sort(cake,cake+n,cmp); //按單價從高到低排序 double ans=0; //收益 for(int i=0;i<n;i++){ if(cake[i].store<=D){ //若是需求量高於月餅庫存量 D-=cake[i].store; //第i種月餅所有賣出 ans+=cake[i].sell; }else{ ans+=cake[i].price*D //只賣出剩餘需求量的月餅 break; } } printf("%.2f\n",ans); return 0; }
貪心code