The numbers 1,2,\dots,n are added to a max-heap in this order. How many swaps of two elements are done on the heap during the process? You may assume that n is at most 10^9.
For example when n=4, the following swaps are performed in this order:
1 \leftrightarrow 2, 2 \leftrightarrow 3, 1 \leftrightarrow 4 and 3 \leftrightarrow 4. Thus the answer is 4.
In a file maxheap.py
, implement a function count
that returns the number of swaps.
def count(n): # TODO if __name__ == "__main__": print(count(4)) # 4 print(count(7)) # 10 print(count(123)) # 618 print(count(999999999)) # 27926258178