-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathnumber-of-effective-subsequences.py
More file actions
33 lines (32 loc) · 1.15 KB
/
number-of-effective-subsequences.py
File metadata and controls
33 lines (32 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Time: O((n + r) * logr), r = max(nums)
# Space: O(n + r)
# sos dp, principle of inclusion and exclusion
class Solution(object):
def countEffective(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MOD = 10**9+7
total = reduce(lambda accu, x: accu|x, nums, 0)
bits = [i for i in xrange(total.bit_length()) if total&(1<<i)]
dp = [0]*(1<<len(bits))
for x in nums:
mask = 0
for i in xrange(len(bits)):
if x&(1<<bits[i]):
mask |= 1<<i
dp[mask] += 1
for i in xrange(len(bits)):
for mask in xrange(len(dp)):
if mask&(1<<i):
dp[mask] += dp[mask^(1<<i)]
cnt = [0]*(1<<len(bits))
for mask in xrange(1, len(cnt)):
cnt[mask] = cnt[mask&(mask-1)]+1
pow2 = [0]*(len(nums)+1)
pow2[0] = 1
for i in xrange(len(nums)):
pow2[i+1] = (pow2[i]*2)%MOD
full = (1<<len(bits))-1
return reduce(lambda accu, x: (accu+x)%MOD, ((1 if cnt[mask]&1 else -1)*pow2[dp[full^mask]] for mask in xrange(1, len(cnt))), 0)