下面是修改后的代码,以实现题目描述的功能:#include <iostream>#include <vector>using namespace std;void solve() { int n, x; cin >> n; vector<int> a[2]; // 使用数组保存 0 和 1 的下标 for (int i = 1; i <= n; i++) { cin >> x; a[x].push_back(i); } int cnt = 0, maxn = 0; int num = a[1].size(); for (int j = 1; j < num; j++) { if (a[1][j] - a[1][j - 1] > 1) { cnt++; } } maxn = max(maxn, cnt); cout << num - maxn << endl;}int main() { int t; cin >> t; while (t--) { solve(); } return 0;}
修改说明:
- 添加了包含必要头文件<iostream>和<vector>。
- 将变量cnt和maxn的初始化移到solve()函数内部。
- 在solve()函数中,将输入变量n和x的声明移至函数内部。
- 修改了统计相邻1之间距离大于1的个数的逻辑,并更新最大值maxn。
- 添加输出语句cout << num - maxn << endl;,输出结果。
希望以上回答对你有所帮助。如果你还有其他问题,请随时提问。 |