目录
1.Problem
Given two integers nn and xx, construct an array that satisfies the following conditions:
- for any element aiai in the array, 1≤ai<2n1≤ai<2n;
- there is no non-empty subsegment with bitwise XOR equal to 00 or xx,
- its length ll should be maximized.
A sequence bb is a subsegment of a sequence aa if bb can be obtained from aa by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
2.Input
The only line contains two integers nn and xx (1≤n≤181≤n≤18, 1≤x<2181≤x<218).
3.Output
The first line should contain the length of the array ll.
If ll is positive, the second line should contain ll space-separated integers a1a1, a2a2, ……, alal (1≤ai<2n1≤ai<2n) — the elements of the array aa.
If there are multiple solutions, print any of them.
4.Examples
4.1input
3 5
4.2output
3
6 1 3
5.Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int readint() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int main() {
int n = readint();
int x = readint();
vector<bool> fb(1 << n, false);
vector<int> ans;
fb[0] = fb[x] = true;
int now = 1, lst = 0;
for (int i = 1; i < (1 << n); i++) {
while (now < (1 << n) && fb[now]) now++;
if (now == (1 << n)) break;
ans.push_back(now ^ lst);
fb[now] = fb[now ^ x] = true;
lst = now;
}
int cnt = ans.size();
printf("%d\n", cnt);
if (cnt > 0) {
for (int i = 0; i < cnt; i++) printf("%d ", ans[i]);
printf("\n");
}
return 0;
}
6.Conclusion
这段代码的主要目的是生成一个由不同的整数构成的序列,并且满足这个序列中的任意两个相邻的元素按位异或的结果不等于预先给定的整数x。生成的序列的长度为2^n,其中n是通过标准输入读取的整数。
以下是代码的主要逻辑:
通过
readint
函数读取输入的两个整数n
和x
,其中n
表示生成序列的长度,而x
是给定的整数。使用一个名为
fb
的布尔型vector
数组,用于标记已经出现的整数。数组的大小为2^n,初始时所有元素都标记为false
。初始化
now
和lst
分别为1和0。now
用于表示当前要加入序列的整数,而lst
用于记录上一个加入序列的整数。使用循环生成序列。在每次循环中,找到下一个未被标记的整数,并计算它与上一个整数的异或值。将这个值加入
ans
数组,并更新标记数组。输出生成的序列的长度
cnt
。如果生成的序列长度大于0,输出序列中的每个整数。
总体来说,这段代码的作用是生成一个满足条件的整数序列,其中序列长度为2^n,每个整数满足与前一个整数的异或值不等于给定的整数x。生成的序列长度和序列本身通过标准输出打印。