如何有效地为每个i和j执行[i&j] + = b [i] * c [j]?

问题描述 投票:1回答:1

我有两个整数数组bc,大小小于1024.我想有效地找到一个新的数组a,这样我每隔0 <= i,j <= 1024就有a[i&j] += b[i] * c[j]。我正在寻找其他解决方案比常规的O(n ^ 2)。

基本上我希望改进这个:

for(int i = 0; i < 1024; ++i){
   for(int j = 0; j < 1024; ++j){
      a[i&j] += b[i] * c[j];
   }
}
bit-manipulation bitmask
1个回答
1
投票

我不敢。由于你想为b[i]c[j]的每种可能组合添加ij,你必须遍历所有这些组合。但是,你可以改进。

如果你只想要一个特定的a[n],而不是整个数组a,那么有更好的方法。

int n = 666; // Input
// Split input into bits
int e[10] = {};
for (int i = 0, ne = 0; i < 10; i++) {
    if ((n & (1<<i)) == 0)
        e[ne++] = i; // Store the indices of zero bits of input
}

现在从输入创建b[i]c[j]

int i, j;
// Enumerate all possible combinations of i and j
for (int count = 0; count < pow(3, ne); count++){
    int t = count;
    i = j = 0;
    for (int k = 0; k < ne; k++) {
        switch (t % 3) {
            case 0: break;
            case 1:
                i |= 1 << k;
                break;
            case 2:
                j |= 1 << k;
                break;
        }
        t /= 3;
    }
    i |= n, j |= n;
    a[n] += b[i] * c[j];
}
© www.soinside.com 2019 - 2024. All rights reserved.