- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 100 lines of Python from the credited upstream file sum-of-beautiful-subsequences.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56MOD = 10**9+77class BIT(object): 8 def __init__(self, n):9 self.__bit = [0]*(n+1) 10 11 def add(self, i, val):12 i += 1 13 while i < len(self.__bit):14 self.__bit[i] = (self.__bit[i]+val) % MOD15 i += (i & -i)16 17 def query(self, i):18 i += 1 19 ret = 020 while i > 0:21 ret = (ret+self.__bit[i]) % MOD22 i -= (i & -i)23 return ret24 25 26def factors(n): 27 result = [[] for _ in xrange(n+1)]28 for i in xrange(1, n+1):29 for j in range(i, n+1, i):30 result[j].append(i)31 return result32 33 34def phi_sieve(n): 35 phi = range(n+1)36 for i in xrange(2, n+1):37 if phi[i] != i:38 continue39 for j in xrange(i, n+1, i):40 phi[j] -= phi[j]i41 return phi42 43 44MAX_NUM = 7 * 10**445FACTORS = factors(MAX_NUM)46PHI = phi_sieve(MAX_NUM)47class Solution(object):48 def totalBeauty(self, nums):49 """50 :type nums: List[int]51 :rtype: int52 """53 def count(arr):54 for i, x in enumerate(sorted(arr)): 55 val_to_idx[x] = i56 bit = BIT(len(arr))57 for x in arr:58 bit.add(val_to_idx[x], bit.query(val_to_idx[x]-1)+1)59 return bit.query(len(arr)-1)60 61 mx = max(nums)62 val_to_idx = [0]*(mx+1)63 lookup = [[] for _ in xrange(mx+1)]64 for x in nums:65 for d in FACTORS[x]:66 lookup[d].append(x)67 return reduce(lambda accu, x: (accu+x)%MOD, (PHI[g]*count(lookup[g]) for g in reversed(xrange(1, mx+1))), 0)68 69 7071727374class Solution2(object):75 def totalBeauty(self, nums):76 """77 :type nums: List[int]78 :rtype: int79 """80 def count(arr):81 val_to_idx = {x:i for i, x in enumerate(sorted(set(arr)))} 82 bit = BIT(len(val_to_idx))83 for x in arr:84 bit.add(val_to_idx[x], bit.query(val_to_idx[x]-1)+1)85 return bit.query(len(val_to_idx)-1)86 87 mx = max(nums)88 lookup = [[] for _ in xrange(mx+1)]89 for x in nums:90 for d in FACTORS[x]:91 lookup[d].append(x)92 result = 093 cnt = [0]*(mx+1)94 for g in reversed(xrange(1, mx+1)):95 cnt[g] = count(lookup[g])96 for ng in xrange(g+g, mx+1, g):97 cnt[g] -= cnt[ng]98 result = (result+g*cnt[g])%MOD99 return result100