酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

c++题目描述 御坂正在玩一个电脑游戏。他的角色正在杀死一些怪物。有n 个怪物,编号从1−n ,第i 个怪物最初的生命值为ai 。 御坂的角色可以对当前生命值最高的怪物造成k 点伤害。如果其中有几个,则选择编号较小的一个。如果怪物的生命值小于或等于0,在御坂使用他的能力后,它就会死亡。 御坂使用他的能力,直到所有怪物死亡。你的任务是确定怪物死亡的顺序。 输入描述 第一行是怪物的数量n(1≤n≤3×105) 和御坂每次可以对怪物造成的伤害k(1≤k≤109) 。 第二行是每个怪物的生命值ai(1≤ai≤109) 。 输出描述 输出怪物的死亡顺序

要解决这个问题,我们需要模拟御坂对怪物造成伤害的过程,并记录每个怪物的死亡顺序。我们可以使用一个优先队列(最大堆)来高效地找到当前生命值最高的怪物。 以下是详细的步骤和C++代码实现: 1. 输入处理:读取怪物的数量 `n` 和每次可以造成的伤害 `k`,然后读取每个怪物的生命值。 2. 优先队列:使用一个优先队列来存储怪物的生命值及其索引。优先队列按照生命值从大到小排序,如果生命值相同则按索引从小到大排序。 3. 模拟过程: - 每次从优先队列中取出生命值最高的怪物,对其造成 `k` 点伤害。 - 如果怪物的生命值大于0,则将其重新插入优先队列。 - 记录死亡的怪物的顺序。 4. 输出结果:输出所有怪物的死亡顺序。 下面是完整的C++代码实现: ```cpp #include <iostream> #include <vector> #include <queue> #include <tuple> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } // Priority queue to store monsters as (-life_value, index) priority_queue<pair<int, int>> pq; for (int i = 0; i < n; ++i) { pq.push({-a[i], i}); } vector<int> death_order; while (!pq.empty()) { auto [neg_life, index] = pq.top(); pq.pop(); int life = -neg_life; // Record the death order of the monster death_order.push_back(index + 1); // +1 to convert to 1-based index // If there are more monsters in the queue, process the next one if (!pq.empty()) { auto [next_neg_life, next_index] = pq.top(); pq.pop(); int next_life = -next_neg_life; // Apply damage to the next highest life monster next_life -= k; // If the next monster is still alive, push it back into the queue if (next_life > 0) { pq.push({-next_life, next_index}); } } } // Output the death order for (int i = 0; i < n; ++i) { cout << death_order[i] << " "; } cout << endl; return 0; } ``` 解释代码逻辑: 1. 输入部分:读取 `n` 和 `k`,以及每个怪物的生命值 `a`。 2. 优先队列初始化:将每个怪物的生命值和索引以负数形式存入优先队列,这样优先队列会按照生命值从大到小排序。 3. 模拟过程: - 每次从优先队列中取出生命值最高的怪物,记录其死亡顺序。 - 对下一个最高生命值的怪物造成 `k` 点伤害,如果该怪物仍然活着,则重新插入优先队列。 4. 输出部分:输出所有怪物的死亡顺序。 这个算法的时间复杂度主要取决于优先队列的操作,每次插入和删除操作的时间复杂度为 O(log n),因此整体时间复杂度为 O(n log n),适用于题目给定的数据范围。 [2025-02-06 19:47:02 | AI写代码神器 | 874点数解答]

相关提问