C++ 中的蛮力方法 O(2^(2k)):
int n = 32 // or any other power of 2
for(int i = 0; i < n; i++){
// we check with which vertices is it connected
for(int j = 0; j < i; j++){
// we stop when j >= i, because we want to output each unordered pair once
int u = i ^ j;
// we check if U is a power of 2, by rounding it up to next power of two and
// checking if it changed
int k = u - 1;
k |= k >> 1;
k |= k >> 2;
k |= k >> 4;
k |= k >> 8;
k |= k >> 16;
if(k + 1 == u)
cout << i << " " << j << endl;
}
}
如果您需要更快的解决方案,我建议您尝试递归,因为超立方体的结构本身就是递归的:n 维超立方体由两个 n-1 维超立方体组成,它们仅在一个坐标上不同。以一个正方形为例 - 它由两个在一个坐标上不同的段(一维)组成。
递归解决方案的算法将或多或少像这样(python):
# outputs pair (list of vertices, list of connections beetween them), for n
# dimensional hypercube with vertices starting at x
def hypercube(n, i):
if n == 1:
return (i, [])
v1, e1 = hypercube(n-1, i)
v2, e2 = hypercube(n-1, i + len(v1))
return(v1 + v2, zip(v1, v2) + e1 + e2)