python为什么拉跨了
查看原帖
python为什么拉跨了
111048
LightString楼主2020/10/18 20:44
class BIT: #Binary Indexed Tree
    __c = [0]
    def __init__(self, n):
        self.__c *= n + 2
    def __lowbit(self, x):
        return x & (-x)
    def Add(self, pos, x):
        while pos < len(self.__c):
            self.__c[pos] += x
            pos += self.__lowbit(pos)
    def Sum(self, pos):
        ans = 0
        while pos > 0:
            ans += self.__c[pos]
            pos -= self.__lowbit(pos)
        return ans
n = int(input())
a = list(map(int, input().split()))
tmp = a[:]
tmp.sort()
h = {}
for i in range(n):
    h[tmp[i]] = i + 1
tree = BIT(n)
ans = 0
for i in range(n-1, -1, -1):
    tree.Add(h[a[i]], 1)
    ans += tree.Sum(h[a[i]] - 1)
print(ans)
2020/10/18 20:44
加载中...