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)

use std::io;

/// ベクトル1はleft...mid-1まで、ベクトル2はmid...right-1まで
/// 昇順に整列済みのベクトル1、ベクトル2を結合する。
fn merge(vec: &mut Vec<u32>, left: usize, mid:usize, right: usize) -> u32 {
    let n = right - left;
    let mut tv: Vec<u32> = vec![0; n];
    for i in 0..(mid-left) {
        tv[i] = vec[left+i];
    }
    for i in 0..(right-mid) {
        tv[n-1-i] = vec[mid+i];
    }

    let mut l = 0;
    let mut r = n - 1;
    let mut cnt = 0;
    for i in left..right {
        if tv[l] < tv[r] {
            vec[i] = tv[l];
            l += 1;
        } else {
            vec[i] = tv[r];
            if r > 0 {
                r -= 1;
            }
        }
        cnt +=1 ;
    }
    cnt
}

fn merge_sort(vec: &mut Vec<u32>, left: usize, right: usize) -> u32 {
    let mut cnt = 0;
    if right - left >= 2 {
        let mid = (left + right) / 2;
        cnt += merge_sort(vec, left, mid);
        cnt += merge_sort(vec, mid, right);
        cnt += merge(vec, left, mid, right);
    }
    cnt
}

fn main() {
    let sin = io::stdin();
    let mut buf = String::new();
    sin.read_line(&mut buf).ok();
    let _n: usize = buf.trim().parse().unwrap();

    let mut buf = String::new();
    sin.read_line(&mut buf).ok();
    let mut s: Vec<u32> = buf.split_whitespace()
        .map(|v| v.parse().unwrap())
        .collect::<Vec<u32>>();
    let size = s.len();
    let cnt = merge_sort(&mut s, 0, size);
    let out = s.iter().map(|v| v.to_string())
        .collect::<Vec<String>>()
        .join(" ");
    println!("{}", out);
    println!("{}", cnt);
}