Python : 树状数组模版


def createTree(array) :
    _array = [0] + array
    length = len(array)
    for i in range(1,length+1) :
        j = i + (i & -i)
        if j < length + 1 :
            _array[j] += _array[i]
    return _array

def lowbit(x) :
    return x & (-x)

def update(idx,val,_array) :
    prev = query(idx,idx+1,_array) 
    idx += 1
    val -= prev
    while idx < len(_array) :
        _array[idx] += val
        idx += lowbit(idx)
    return _array

def query(begin,end,_array) :
    return _query(end,_array) - _query(begin,_array)

def _query(idx,_array) :
    res = 0
    while idx > 0 :
        res += _array[idx]
        idx -= lowbit(idx)
    return res

numList = [1,5,4,2,3]
newList = createTree(numList) 
print(newList)
print(query(2,4,newList))

你可能感兴趣的:(Python,python,算法)