注解
1、贪心策略:按单价降序排序。
2、排序后,对每个物品,如果该物品体积大于所需总体积,就用单价乘所需总体积。否则,就用单价乘该物品体积。直到所需体积为0。
代码
#include <iostream>
#include <algorithm>
using namespace std;
struct Thing{
int pi;
int mi;
};
int compare(Thing t1, Thing t2){
return t1.pi>t2.pi;
}
int main(){
int v;
cin>>v;
while(v){
int n;
cin>>n;
Thing th[n];
for(int i=0; i<n; i++){
cin>>th[i].pi>>th[i].mi;
}
sort(th, th+n, compare);
int ans = 0;
for(int i=0; i<n; i++){
if(th[i].mi<=v){
v -= th[i].mi;
ans += th[i].pi*th[i].mi;
}
else{
ans += th[i].pi*v;
v = 0;
break;
}
}
cout<<ans<<endl;
cin>>v;
}
return 0;
}