-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvnum.py
More file actions
34 lines (32 loc) · 860 Bytes
/
invnum.py
File metadata and controls
34 lines (32 loc) · 860 Bytes
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
34
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
def invnum(n,a):
bit=fenwick_tree(n)
res=0
for j in range(n):
res+=j-bit.sum0(a[j])
bit.add(a[j],1)
return res
def inv_num(A):
S=[(A[i],i) for i in range(len(A))]
S.sort()
return invnum(len(A),[s[1] for s in S])