题面
You are given a binary string of length . You can perform the following operation on the string:
- Choose an index , and flip the bit present at all other indices except for the index . In other words, choose an integer (), and for all such that and , if , then set , otherwise set .
You can perform the operation any number of times, but each index can be chosen by at most one operation.
Your task is to make all bits present in the string equal , or report that it is impossible to do so. You don’t have to minimize the number of operations.
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains a single integer ().
The second line of each test case contains the binary string of length .
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output if it is impossible to transform all bits to . Otherwise, output two lines in the following format:
- In the first line, print the number of operations ().
- In the second line of each test case, print numbers – the indices you select in each operation in order. You should guarantee that each index is chosen at most once.
If there are multiple possible solutions, you may output any.
思路
这题最关键的是把“操作”翻译成按位异或关系
我们设一个变量 ,表示下标 是否被选择进行操作:
- :这个下标被选过一次
- :这个下标没被选
对于任意一个位置 ,它会被所有 的操作翻转,因此最终状态满足:
我们再定义总异或:
那么就有:
题目要求最终全为 ,即 ,代入可得:
这句话很重要:只要 确定,所有 都被唯一确定
接下来做可行性判断,对上式整体异或:
设 (也就是字符串里 的个数奇偶性),分情况:
- 当 为偶数时:,一定有解
- 当 为奇数时:推出必须 ,否则无解
因此无解条件只有一个: 为奇数且 的个数为奇数
构造方式也就很直接:
- 先求
- 如果 是奇数且 ,输出
- 否则可行,取
- 偶数 :
- 奇数 :可取
- 按照 逐位计算,若 ,就把下标 放进答案
最终答案数组里的下标就是要执行操作的位置,每个下标最多出现一次,完全符合题意
代码
#include <bits/stdc++.h>
using namespace std;
int main() { int t; cin >> t; while (t --) { int n; string s; cin >> n >> s; int pp = 0; for (auto c: s) { if (c == '1') pp ++; } int p = pp % 2; if (n % 2 != 0 && p == 1) cout << -1 << endl; else { int k; if (p == 1) k = 1; else k = p; vector<int> ans, x; for (int i = 0; i < n; i ++) { x.push_back((s[i] - '0') ^ k); if (x[i] == 1) ans.push_back(i + 1); } cout << ans.size() << '\n'; for (int i = 0; i < (int)ans.size(); i++) { cout << ans[i] << " \n"[i == (int)ans.size() - 1]; } if (ans.empty()) cout << '\n'; } }}