题目
思路
贪心 - OI Wiki (oi-wiki.org)
贪心算法(greedy algorithm,又称贪婪算法)详解(附例题)-CSDN博客
代码
Python暴力排序
def min_mora_cost(n, levels):levels.sort() # 对圣遗物等级进行升序排序total_cost = 0 # 初始化总摩拉消耗数为0# 进行强化操作直到只剩下一件超级圣遗物为止while len(levels) > 1:# 选择等级最低的两件圣遗物进行强化current_cost = levels[0] + levels[1]total_cost += current_cost# 合成新的圣遗物,将其等级加入到原有的圣遗物集合中levels = levels[2:] + [current_cost]levels.sort() # 重新排序圣遗物等级列表return total_cost# 读取输入
n = int(input())
levels = list(map(int, input().split()))# 输出最小的摩拉消耗值
print(min_mora_cost(n, levels))
C++暴力贪心
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;int main() {int n;cin >> n;vector<int> relics(n);for (int i = 0; i < n; ++i) {cin >> relics[i];}// 对圣遗物的等级进行排序sort(relics.begin(), relics.end());int total_cost = 0;while (relics.size() > 1) {// 选择最小等级的两个圣遗物进行强化int cost = relics[0] + relics[1];total_cost += cost;// 将新的圣遗物加入列表,并重新排序relics.push_back(cost);sort(relics.begin() + 2, relics.end());// 移除已经强化的两个圣遗物relics.erase(relics.begin(), relics.begin() + 2);}cout << total_cost << endl;return 0;
}
C++优先队列
#include <iostream>
#include <vector>
#include <queue>using namespace std;int main() {int n;cin >> n;// 读取圣遗物的等级,同时构建优先队列priority_queue<int, vector<int>, greater<int>> pq;for (int i = 0; i < n; ++i) {int level;cin >> level;pq.push(level);}int total_cost = 0;// 当优先队列中至少有两个元素时,不断取出两个最小等级的圣遗物进行强化while (pq.size() >= 2) {// 取出队首的两个最小等级的圣遗物int relic1 = pq.top();pq.pop();int relic2 = pq.top();pq.pop();// 计算强化的摩拉消耗,并将新的圣遗物加入到队列中int cost = relic1 + relic2;total_cost += cost;pq.push(cost);}cout << total_cost << endl;return 0;
}