可以使用优先队列,好处是卖完时队列为空自动退出。
键为pair<double,int>,按first 单价排序,second值为下标i,直接可以索引输入的两个数组位置。
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
vector<double> a(n),b(n);
priority_queue<pair<double, int>> q;
for (int i = 0; i < n;++i){
cin >> a[i];
}
for (int i = 0; i < n;++i){
cin >> b[i];
q.emplace(b[i]/a[i],i);
}
double ans = 0;
while(!q.empty()&&m>0){
auto[x,i] = q.top();
q.pop();
if(a[i]<=m){
m -= a[i];
ans += b[i];
}else{
ans += m * x;
m = 0;
}
}
printf("%.2f", ans);
}