# Python 3 program for the above approach
import sys
# Stores the maximum integer of the sets
# for each query
maxAns = -sys.maxsize - 1
# Function to perform the find operation
# of disjoint set union
def Find(parent, a):
if(parent[a] == a):
return a
return Find(parent, parent[a])
# Function to perform the Union operation
# of disjoint set union
def Union(parent, rank,
setSum, a, b):
# Find the parent of a and b
a = Find(parent, a)
b = Find(parent, b)
if (a == b):
return
if (rank[a] > rank[b]):
rank[a] += 1
if (rank[b] > rank[a]):
swap(a, b)
# Update the parent
parent[b] = a
# Update the sum of set a
setSum[a] += setSum[b]
# Function to find the maximum element
# from the sets after each operation
def maxValues(arr,
queries, N):
global maxAns
# Stores the parent elements of
# the sets
parent = [0]*(N + 1)
# Stores the rank of the sets
rank = [0]*(N + 1)
# Stores the sum of the sets
setSum = [0]*(N + 1)
# Stores the maximum element for
# each query
currMax = []
for i in range(1, N + 1):
# Initially set is empty
parent[i] = -1
# Update the sum as the
# current element
setSum[i] = arr[i - 1]
# After the last query set will
# be empty and sum will be 0
currMax.append(0)
for i in range(N - 1, 0, -1):
# Check if the current element
# is not in any set then make
# parent as current element
# of the queries
if (parent[queries[i]] == -1):
parent[queries[i]] = queries[i]
# Check left side of the queries[i]
# is not added in any set
if (queries[i] - 1 >= 0
and parent[queries[i] - 1] != -1):
# Add the queries[i] and the
# queries[i]-1 in one set
Union(parent, rank, setSum,
queries[i],
queries[i] - 1)
# Check right side of the queries[i]
# is not added in any set
if (queries[i] + 1 <= N
and parent[queries[i] + 1] != -1):
# Add queries[i] and the
# queries[i]+1 in one set
Union(parent, rank, setSum,
queries[i],
queries[i] + 1)
# Update the maxAns
maxAns = max(setSum[queries[i]], maxAns)
# Push maxAns to the currMax
currMax.append(maxAns)
# Print currMax values in the
# reverse order
for i in range(len(currMax) - 1, -1, -1):
print(currMax[i], end=" ")
# Driver Code
if __name__ == "__main__":
arr = [1, 3, 2, 5]
queries = [3, 4, 1, 2]
N = len(arr)
maxValues(arr, queries, N)
# This code is contributed by ukasp.