import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Main{ public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int n; double need; double sum=0; String s[]=in.readLine().split(" "); n=Integer.parseInt(s[0]); need=Double.parseDouble(s[1]); String amount[]=in.readLine().split(" "); String price[]=in.readLine().split(" "); ArrayList<Mooncake> cakes=new ArrayList<Mooncake>(); for(int i=0;i<n;i++){ Mooncake cake=new Mooncake(); cake.setAmount(Double.parseDouble(amount[i])); cake.setSales(Double.parseDouble(price[i])); cake.setValues(Double.parseDouble(price[i])/Double.parseDouble(amount[i])); cakes.add(cake); } Collections.sort(cakes); for(Mooncake c: cakes){ if(need>=c.amount){ need=need-c.amount; sum+=c.amount*c.values; } else{ sum+=need*c.values; need=0; } if(need==0){ break; } } System.out.printf("%.2f",sum); } static class Mooncake implements Comparable<Mooncake>{ double amount; double sales; double values; public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public double getSales() { return sales; } public void setSales(double sales) { this.sales = sales; } public double getValues() { return values; } public void setValues(double values) { this.values = values; } @Override public int compareTo(Mooncake arg0) { // TODO Auto-generated method stub return this.values>arg0.values?-1:1; } } }转c++
时间: 2023-07-15 17:14:26 浏览: 151
java.io.Reader 和 java.io.InputStream 的区别
4星 · 用户满意度95%
把Java代码转换成C++代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Mooncake {
double amount;
double sales;
double values;
bool operator<(const Mooncake& c) const {
return this->values > c.values;
}
};
int main() {
int n;
double need, sum = 0;
cin >> n >> need;
vector<Mooncake> cakes(n);
for (int i = 0; i < n; i++) {
cin >> cakes[i].amount;
}
for (int i = 0; i < n; i++) {
double price;
cin >> price;
cakes[i].sales = price;
cakes[i].values = price / cakes[i].amount;
}
sort(cakes.begin(), cakes.end());
for (const auto& c : cakes) {
if (need >= c.amount) {
need = need - c.amount;
sum += c.amount * c.values;
}
else {
sum += need * c.values;
need = 0;
}
if (need == 0) {
break;
}
}
printf("%.2f", sum);
return 0;
}
阅读全文