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 C# (judge verdict: Time Limit Exceeded)

using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;


public class my
{
	public static void Main()
	{
		var n = my.GetInt();
		var A = my.GetIntArray(n);
		
		var cnt = my.MergeSort(A, 0, n);
		
		my.WriteArray(A);
		Console.WriteLine(cnt);
	}
	
	private static int MergeSort(int[] A, int left, int right)
	{
		int cnt = 0;
		
		if(left +1 < right) {
			int mid = (left + right) / 2;
			
			cnt += my.MergeSort(A, left, mid);
			cnt += my.MergeSort(A, mid, right);
			cnt += my.Merge(A, left, mid, right);
		}
		
		return cnt;
	}
	
	private static int Merge(int[] A, int left, int mid, int right)
	{
		var n1 = mid - left;
		var n2 = right - mid;
		
		var L = A.Skip(left).Take(n1+1).ToArray();
		var R = new int[n2 + 1];	// for sentinel
		Array.Copy(A, mid, R, 0, n2);
		L[n1] = int.MaxValue;	// Sentinel
		R[n2] = int.MaxValue;
		
		int i = 0, j=0;
		
		int cnt = 0;
		for(int k = left; k < right; k++) {
			if(L[i] <= R[j]) {
				A[k] = L[i++];
			} else {
				A[k] = R[j++];
			}
			cnt++;
		}
		
		return cnt;
	}

	
	private static int CountChar(string s, char c)
	{
		return s.Length - s.Replace(c.ToString(), "").Length;
	}

	private static int[] GetIntArray()
	{
		return Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
	}
		
	private static int[] GetIntArray(int n)
	{
		var A = new int[n];
		var s = Console.ReadLine().Split(' ');
		
		for(int i = 0; i < n; i++) {
			A[i] = int.Parse(s[i]);
		}
		return A;
	}
	
	private static void WriteArray(int[] a)
	{
		Console.WriteLine(string.Join(" ", Array.ConvertAll( a, x=>x.ToString() ) ) );
	}
	
	private static void WriteArray(long[] a)
	{
		Console.WriteLine(string.Join(" ", Array.ConvertAll( a, x=>x.ToString() ) ) );
	}
	
	private static int GetInt()
	{
		return int.Parse(Console.ReadLine());
	}
	
	private static long GetLong()
	{
		return long.Parse(Console.ReadLine());
	}
}