rt,代码如下:
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// 珠子结构体,存储珠子的能量值和珠子编号
struct Bead {
int energy;
int num;
};
// 重载运算符,用于排序珠子的顺序(按照能量值从大到小排序)
bool operator<(const Bead& a, const Bead& b) {
return a.energy < b.energy;
}
int main() {
int n;
cin >> n;
// 读入珠子的能量值
vector<Bead> beads(n);
for (int i = 0; i < n; i++) {
cin >> beads[i].energy;
beads[i].num = i + 1;
}
// 将珠子按照能量值从大到小排序
sort(beads.begin(), beads.end());
// 创建最大堆,用于保存珠子
priority_queue<Bead> max_heap;
for (int i = 0; i < n; i++) {
max_heap.push(beads[i]);
}
// 逐个合并珠子
int total_energy = 0;
while (max_heap.size() > 1) {
Bead b1 = max_heap.top();
max_heap.pop();
Bead b2 = max_heap.top();
max_heap.pop();
int combined_energy = b1.energy + b2.energy;
total_energy += combined_energy;
// 合并珠子,并重新加入最大堆中
max_heap.push({ combined_energy, 0 });
}
cout << total_energy << endl;
return 0;
}