```cpp #include <iostream> #include <vector> #include <unordered_map> using namespace std; int minOperationsToEmptyArray(int n, const vector<int>& a) { unordered_map<int, int> countMap; for (int num : a) { countMap[num]++; } // 记录最大连续相同元素长度 int maxConsecutive = 0; int currentConsecutive = 1; for (int i = 1; i < n; ++i) { if (a[i] == a[i - 1]) { currentConsecutive++; } else { maxConsecutive = max(maxConsecutive, currentConsecutive); currentConsecutive = 1; } } maxConsecutive = max(maxConsecutive, currentConsecutive); // 如果存在超过2个的连续相同元素,直接返回这些元素的数量除以2向上取整 if (maxConsecutive > 2) { return (n + 1) / 2; } // 如果所有元素都不同或者最多有两个连续相同的元素 int uniqueElements = countMap.size(); if (uniqueElements == n) { return n - 1; } else { return uniqueElements; } } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int& num : a) { cin >> num; } cout << minOperationsToEmptyArray(n, a) << endl; } return 0; } ``` 代码 - 使用 `unordered_map` 统计每个元素出现次数。 - 遍历数组,记录最大连续相同元素长度。 - 根据最大连续相同元素长度判断操作次数。 - 对于测试用例,循环读入数据并输出结果。 额外需要注意的地方: 1. 输入数据量较大时,使用快速读写方法优化性能。 2. 处理边界情况,如数组长度为1或所有元素相同。 3. 考虑到内存限制,避免不必要的空间开销。 [2024-12-21 17:35:25 | AI写代码神器 | 462点数解答]