以下是使用另一种方法实现的代码:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
struct LNode {
int month;
int day;
string name;
double price;
LNode(int a, int b, string c, double d) : month(a), day(b), name(c), price(d) {}
};
class List {
public:
vector<LNode*> nodes;
void insert(LNode* node) {
nodes.push_back(node);
}
void insert(int index, LNode* node) {
if (index >= 0 && index <= nodes.size()) {
nodes.insert(nodes.begin() + index, node);
}
}
void print_L() {
for (LNode* node : nodes) {
cout << node->month << " " << node->day << " ";
}
cout << endl;
}
int located(int a, int b) {
for (int i = 0; i < nodes.size(); i++) {
if (a < nodes[i]->month || (a == nodes[i]->month && b < nodes[i]->day)) {
return i + 1;
}
}
return nodes.size() + 1;
}
};
int main() {
int m, n;
string str;
string c;
double d;
cin >> m >> n;
List L1;
double ave1 = 0.0;
double ave2 = 0.0;
for (int i = 0; i < m; i++) {
cin >> str >> c >> d;
int a = stoi(str.substr(2));
int b = stoi(str.substr(0, 2));
LNode* newNode = new LNode(a, b, c, d);
int e = L1.located(a, b);
L1.insert(e, newNode);
}
double sum1 = 0.0;
int count1 = 0;
double sum2 = 0.0;
int count2 = 0;
for (LNode* node : L1.nodes) {
if (count1 >= n && count2 >= n) {
break;
}
if (node->name == "keyboard" && count1 < n) {
sum1 += node->price;
count1++;
}
if (node->name == "mouse" && count2 < n) {
sum2 += node->price;
count2++;
}
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
这段代码与原始代码的功能相同,但使用了更现代化和简洁的C++语法和数据结构。
内容由零声教学AI助手提供,问题来源于学员提问