Problem:
Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes

Solution in Ruby (judge verdict: WA: Presentation Error)

def mergesort array_A,left,right
  if left+1 < right
  mid = (left+right)/2
  mergesort(array_A,left,mid)
  mergesort(array_A,mid,right)  
  merge(array_A,left,mid,right) 
  end
end

def merge array_A,left,mid,right
n1 = mid - left
n2 = right - mid
array_L,array_R = Array.new(),Array.new()
n1.times {|i|
array_L[i] = array_A[left+i]
}
n2.times {|i|
  array_R[i] = array_A[mid+i]
}
array_L[n1],array_R[n2]=(10**9).next,(10**9).next
j,i=0,0
p = right - left
p.times {|k|
  if array_L[i] <= array_R[j]
  array_A[left+k]=array_L[i]
  i+=1
  else
  array_A[left+k]=array_R[j]
  j+=1
  end
}
$count +=  p
end
n = gets.chomp.to_i
$count = 0
array_A = gets.split(" ").map{|x|x.to_i}
mergesort(array_A,0,n)
q = array_A.count {|item| !item.nil? }
q.times {|i|
  printf("%d ",array_A[i])
}
printf("\n%d",$count)