We're given number N - length of the next list (1 <= N <= 10^5).
Then there is a list of N numbers (1 <= num <= 10^9).
The task is to find median on each iteration through 1 to N (on the i-th iteration we find median of sub-array lst[:i]) and then to find the sum of all N medians.
Exampes
Input:
10
5 10 8 1 7 3 9 6 2 4
Output:
59 (5+5+8+5+7+5+7+6+6+5)
Input2:
5
5 3 1 2 4
Output2:
16 (5+3+3+2+3)
Approach for better solution - Sum of medians - here was offered to use BinarySearchTrees and I did it.
But it wasn't enough to pass 2 sec time limit with these constrictions. Is there a faster solution?
class BinarySearchTree:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def insert(self, value):
if self.value:
if value < self.value:
if self.left is None:
self.left = BinarySearchTree(value)
else:
self.left.insert(value)
elif value > self.value:
if self.right is None:
self.right = BinarySearchTree(value)
else:
self.right.insert(value)
else:
self.value = value
def output_subtree(self):
if self.left:
self.left.output_subtree()
sub_tree.append(self.value)
if self.right:
self.right.output_subtree()
N = int(input())
vertices = list(map(int, input().split()))
medians = 0
tree = BinarySearchTree(vertices[0])
medians += vertices[0]
for i in range(1, N):
sub_tree = []
tree.insert(vertices[i])
tree.output_subtree()
if (i+1) % 2 == 0:
medians += sub_tree[len(sub_tree)//2-1]
else:
medians += sub_tree[len(sub_tree)//2]
print(medians)