酷代码 AI
菜单
服务商

密室攻防大战:计算护盾最少移动次数的 C++ 实现

以下是解决该问题的 C++ 代码: ```cpp #include <iostream> #include <vector> // 计算护盾最少移动次数的函数 int minShieldMoves(int n, int L, int R, std::vector<int> attacks) { int moves = 0; // 遍历每一次攻击 for (int attack : attacks) { // 如果攻击位置在护盾左边 if (attack < L) { // 计算需要向左移动的距离 int moveLeft = L - attack; moves += moveLeft; // 更新护盾的左右端点 L -= moveLeft; R -= moveLeft; } // 如果攻击位置在护盾右边 else if (attack > R) { // 计算需要向右移动的距离 int moveRight = attack - R; moves += moveRight; // 更新护盾的左右端点 L += moveRight; R += moveRight; } } return moves; } int main() { int n, L, R; // 读取密室列数、护盾初始左右端点 std::cin >> n >> L >> R; int m; // 读取攻击次数 std::cin >> m; std::vector<int> attacks(m); // 读取每次攻击的列数 for (int i = 0; i < m; ++i) { std::cin >> attacks[i]; } // 调用函数计算最少移动次数 int result = minShieldMoves(n, L, R, attacks); // 输出结果 std::cout << result << std::endl; return 0; } ``` ### 代码解释: 1. **`minShieldMoves` 函数**: - 该函数接收密室列数 `n`、护盾初始左右端点 `L` 和 `R` 以及攻击列数的向量 `attacks` 作为参数。 - 遍历每一次攻击,根据攻击位置与护盾位置的关系进行处理: - 如果攻击位置在护盾左边,计算需要向左移动的距离并更新护盾的左右端点。 - 如果攻击位置在护盾右边,计算需要向右移动的距离并更新护盾的左右端点。 - 最后返回护盾移动的总次数。 2. **`main` 函数**: - 读取输入的密室列数、护盾初始左右端点、攻击次数和每次攻击的列数。 - 调用 `minShieldMoves` 函数计算最少移动次数。 - 输出结果。 ### 复杂度分析: - **时间复杂度**:$O(m)$,其中 $m$ 是攻击的次数。因为只需要遍历一次攻击列表。 - **空间复杂度**:$O(m)$,主要用于存储攻击列数的向量。 ######[AI问答 | 679点数解答 | 2026-03-14 19:46:56]

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