# Python3 program for the above approach
MAXX = 100
# Declaring segment tree
st = [0] * (4 * MAXX)
# Function to initialize segment tree
# with leaves filled with ones
def build(x, lx, rx):
# Base Case
if (rx - lx == 1):
st[x] = 1
return
# Split into two halves
m = (lx + rx) // 2
# Build the left subtree
build(x * 2 + 1, lx, m)
# Build the right subtree
build(x * 2 + 2, m, rx)
# Combining both left and right
# subtree to parent node
st[x] = st[x * 2 + 1] + st[x * 2 + 2]
return
# Function to make index x to 0
# and then update segment tree
def update(i, x, lx, rx):
# Base Case
if (rx - lx == 1):
st[x] = 0
return
# Split into two halves
m = (lx + rx) // 2
# Update Query
if (i < m):
update(i, x * 2 + 1, lx, m)
else:
update(i, x * 2 + 2, m, rx)
# Combining both left and right
# subtree to parent node
st[x] = st[x * 2 + 1] + st[x * 2 + 2]
return
# Function to find the Kth element
def getans(x, lx, rx, k, n):
# Base Condition
if (rx - lx == 1):
if (st[x] == k):
return lx
return n
# Split into two halves
m = (lx + rx) // 2
# Check if kth one is in left subtree
# or right subtree of current node
if (st[x * 2 + 1] >= k):
return getans(x * 2 + 1, lx, m, k, n)
else:
return getans(x * 2 + 2, m, rx,
k - st[x * 2 + 1], n)
# Function to generate the original
# permutation
def getPermutation(inv, n):
# Build segment tree
build(0, 0, n)
# Stores the original permutation
ans = []
for i in range(n - 1, -1, -1):
# Find kth one
temp = getans(0, 0, n, st[0] - inv[i], n)
# Answer for arr[i]
ans.append(temp + 1)
# Setting found value back to 0
update(max(0, temp), 0, 0, n)
# Print the permutation
for i in range(n - 1, -1, -1):
print(ans[i], end = " ")
return
# Driver Code
if __name__ == '__main__':
# Given array
inv = [ 0, 1, 1, 0, 3 ]
# Length of the given array
N = len(inv)
# Function Call
getPermutation(inv, N)
# This code is contributed by mohit kumar 29