Skip to content

Instantly share code, notes, and snippets.

@shakayami
Created November 30, 2021 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakayami/ffb66821f513dede1880870b7be5c05a to your computer and use it in GitHub Desktop.
Save shakayami/ffb66821f513dede1880870b7be5c05a to your computer and use it in GitHub Desktop.
class fenwick_tree():
n=1
data=[0 for i in range(n)]
def __init__(self,N):
self.n=N
self.data=[0 for i in range(N)]
def add(self,p,x):
assert 0<=p<self.n,"0<=p<n,p={0},n={1}".format(p,self.n)
p+=1
while(p<=self.n):
self.data[p-1]+=x
p+=p& -p
def sum(self,l,r):
assert (0<=l and l<=r and r<=self.n),"0<=l<=r<=n,l={0},r={1},n={2}".format(l,r,self.n)
return self.sum0(r)-self.sum0(l)
def sum0(self,r):
s=0
while(r>0):
s+=self.data[r-1]
r-=r&-r
return s
N=int(input())
a=[int(i) for i in input().split()]
G=fenwick_tree(N)
ans=0
for i in range(N):
ans+=G.sum(a[i],N)
G.add(a[i],1)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment