📌  相关文章
📜  计算所有子数组的按位异或

📅  最后修改于: 2021-05-25 01:11:00             🧑  作者: Mango

给定非负整数数组A ,其中0 \leq A[i] \leq 10^{9} 。任务是计算通过对所有可能的子数组中的所有元素进行按位或运算而获得的不同可能结果的数量。

例子:

Input: A = [1, 2]
Output: 3
Explanation: The possible subarrays are [1], [2], [1, 2].
These Bitwise OR of subarrays are 1, 2, 3.
There are 3 distinct values, so the answer is 3.

Input: A = [1, 2, 4]
Output: 6
Explanation: The possible distinct values are 1, 2, 3, 4, 6, and 7.

方法:
天真的方法是生成所有可能的子数组,并对子数组中的所有元素进行按位“或”运算。将每个结果存储在set中并返回set的长度
高效方法:
我们可以使上述方法更好。天真的方法是计算所有可能的结果,其中res(i,j)= A [i] | A [i + 1] | …| A [j] 。但是,我们可以通过注意到res(i,j + 1)= res(i,j)|来加快速度。 A [j + 1] 。在第k步,假设我们将所有res(i,k)都设置为pre 。然后,通过使用res(i,k + 1)= res(i,k)|,可以找到下一个预设(对于k-> k + 1 )。 A [k + 1]

但是,由于列表res(k,k),res(k-1,k),res(k-2,k),…单调递增的,因此该set pre中唯一值的数量最多为32。与先前值不同的后续值的二进制表示形式中必须有更多1,最多可以有32个值

下面是上述方法的实现。

Python
# Python implementation of the above approach
  
# function to return count of distinct bitwise OR
def subarrayBitwiseOR(A):
  
    # res contains distinct values
    res = set()
  
    pre = {0}
  
    for x in A:
        pre = {x | y for y in pre} | {x}
        res |= pre
  
    return len(res)
  
  
# Driver program
A = [1, 2, 4]
  
# print required answer
print(subarrayBitwiseOR(A))
  
# This code is written by
# Sanjit_Prasad


输出:

6

时间复杂度: O(N * log(K)),其中N是A的长度,K是A中元素的最大大小。