酷代码 AI
菜单
服务商

C++ 实现数字消除游戏,计算最多消除对数

以下是解决该问题的 C++ 代码: ```cpp #include <iostream> using namespace std; int main() { int n; cin >> n; // 用于记录余数为 0、1、2 的数字的个数 int remainder0 = 0, remainder1 = 0, remainder2 = 0; for (int i = 0; i < n; i++) { int num; cin >> num; if (num % 3 == 0) { remainder0++; } else if (num % 3 == 1) { remainder1++; } else { remainder2++; } } // 余数为 0 的数字两两配对 int pairs = remainder0 / 2; // 余数为 1 和余数为 2 的数字配对 pairs += min(remainder1, remainder2); cout << pairs << endl; return 0; } ``` ### 代码解释: 1. **输入处理**:首先读取整数的数量 `n`,然后循环读取 `n` 个整数,统计这些整数除以 3 的余数分别为 0、1、2 的数字的个数。 2. **配对计算**: - 余数为 0 的数字可以两两配对,所以可以配对的对数为 `remainder0 / 2`。 - 余数为 1 和余数为 2 的数字可以相互配对,配对的对数为 `min(remainder1, remainder2)`。 3. **输出结果**:将两种配对方式得到的对数相加,即为最多能消除的数字对数,并输出结果。 ### 复杂度分析: - **时间复杂度**:$O(n)$,其中 $n$ 是输入的整数的数量。 - **空间复杂度**:$O(1)$,只使用了常数级的额外空间。 ######[AI问答 | 454点数解答 | 2026-03-14 20:59:16]

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