酷代码 AI
菜单
服务商

C++实现御坂游戏:优先队列搞定怪物死亡顺序,时间复杂度最优!

```cpp #include <iostream> #include <queue> #include <vector> #include <algorithm> using namespace std; int main() { int n, k; cin >> n >> k; vector<pair<int, int>> monsters; // pair: monster's health, index for (int i = 0; i < n; ++i) { int health; cin >> health; monsters.push_back({health, i + 1}); } // Custom comparator for sorting monsters by health in descending order auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) { return a.first < b.first; }; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp); for (const auto& monster : monsters) { pq.push(monster); } while (!pq.empty()) { pair<int, int> topMonster = pq.top(); pq.pop(); cout << topMonster.second << " "; topMonster.first -= k; // Decrease monster's health after attack if (topMonster.first > 0) { pq.push(topMonster); // Monster still alive, push back to queue } } return 0; } // 需要注意的逻辑点: // 1. 使用优先队列可以方便地选择当前生命值最高的怪物进行攻击。 // 2. 每次攻击后需要检查怪物的生命值,如果大于0则继续放回队列,否则表示怪物已死亡。 // 3. 按照怪物的初始顺序输出死亡顺序。 ``` ######[AI写代码神器 | 861点数解答 | 2025-01-06 19:44:34]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]