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 Rust (judge verdict: Accepted)

fn print_vec(arr: &Vec<i32>) {
    for i in 0..arr.len() {
        print!("{}", arr[i]);
        if i < arr.len() - 1 {
            print!(" ");
        }
    }
}

static mut N_COMPARE: i32 = 0;

fn merge_sort(inputs: &mut Vec<i32>, left: usize, right: usize) -> () {
    if left + 1 >= right {
        return ();
    }
    let middle = (left + right) / 2;
    merge_sort(inputs, left, middle);
    merge_sort(inputs, middle, right);
    merge(inputs, left, middle, right)
}

fn merge(inputs: &mut Vec<i32>, left: usize, middle: usize, right: usize) -> () {
    let n1 = middle - left;
    let n2 = right - middle;
    let infinity: i32 = 2 * 10_f32.powi(9) as i32;
    let mut l = inputs[left..(left + n1)].to_vec();
    let mut r = inputs[middle..(middle + n2)].to_vec();
    l.push(infinity);
    r.push(infinity);

    let mut i = 0 as usize;
    let mut j = 0 as usize;
    for k in left..right {
        if l[i] <= r[j] {
            inputs[k] = l[i];
            i += 1;
        } else {
            inputs[k] = r[j];
            j += 1;
        }
        unsafe {
            N_COMPARE += 1;
        }
    }
}

fn main() {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    let n = line.trim().parse::<usize>().unwrap();

    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    let mut inputs: Vec<i32> = line.split_whitespace()
        .map(|e| e.parse::<i32>().ok().unwrap())
        .collect();

    let (left, right) = (0, n);
    merge_sort(&mut inputs, left, right);

    print_vec(&inputs);
    println!();
    unsafe {
        println!("{}", N_COMPARE);
    }
}