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] 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

Template in C
-->



Sample input:
10
8 5 9 2 6 3 7 1 10 4


Sample output:
1 2 3 4 5 6 7 8 9 10
34

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin

n = int(stdin.readline().rstrip())
*A, = map(int, stdin.readline().split())
cnt = 0

def merge(A, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = [A[left + i] for i in range(n1)]
    R = [A[mid + i] for i in range(n2)]
    L.append(10 ** 9)
    R.append(10 ** 9)
    i = 0
    j = 0
    for k in range(left, right):
        # print(" ".join(map(str,A)))#TODO
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    global cnt
    cnt += right - left  # !

def merge_sort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        merge_sort(A, left, mid)
        merge_sort(A, mid, right)
        merge(A, left, mid, right)

merge_sort(A, 0,n)
print(" ".join(map(str, A)))
print(cnt)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
"""
ソートテク関連の基本的な関数の詰め合わせ (命名は C++ STL algorithm による)


stable_partition(seq, func):
    O(n)
    空間計算量も O(n)
    述語が True を返す全ての要素が、述語が False を返す全ての要素よりも前になるようにシーケンスを並び替える (破壊、安定)


nth_element(seq, k, begin, end):
    O(n)
    E = seq[k] とする
    特定の要素 E よりも小さい全ての要素が E よりも前になり、 E 以上の全ての要素がEよりも後になるように seq[begin:end] を並び替える (破壊、不安定)
    heapq の nlargest とは異なるので注意


ith_order_statistic(seq, i, begin, end):
    O(n)
    nth_element を用いて (seq[begin:end] に存在することがわかっている) i 番目の順序統計量を求める (i = 0, 1, ..., n-1)


simple_quick_sort(seq, begin, end):
    O(nlgn)
    nth_element を用いて seq[begin:end] をソートする (破壊、不安定)


modified_merge_sort(seq, begin, end):
    O(nlgn)
    _modified_merge を用いて seq[begin:end] をソートする (非破壊、安定)
    転倒数とソート済み配列を返す


count_inversion(seq):
    O(nlgn)
    modified_merge_sort を用いて seq の転倒数を求める
    (転倒数: seq[i] > seq[j] (i < j) なる (i, j) の組み合わせの数のこと)
"""


import random
from typing import TypeVar, Callable, List, Tuple, Union
T = TypeVar('T')
Num = Union[int, float]




def _modified_merge(left: List[Num], right: List[Num]) -> Tuple[int, List[Num]]:
    """
    ソート済み配列 left, right を受け取り、全体のソート済み配列を生成する (O(n))
    マージの過程で転倒数をメモして返す

    Args:
        left (list): ソート済み
        right (list): ソート済み

    Returns:
        inv (int): 転倒数
        sorted_list (list): ソート済み
    
    Examples:
        >>> _modified_merge([1, 5, 7], [2, 3, 3])
        (6, [1, 2, 3, 3, 5, 7])
    """
    sorted_list = []
    i, j, inv = 0, 0, 0
    buf_1 = left[:] + [float('inf')]
    buf_2 = right[:] + [float('inf')]
    for _ in range(len(left) + len(right)):
        if buf_1[i] < buf_2[j]:
            sorted_list.append(buf_1[i])
            i += 1
        else:
            sorted_list.append(buf_2[j])
            j += 1
        inv += 1
    return inv, sorted_list


def modified_merge_sort(L, begin, end):
    """
    L[begin:end] を 非破壊的かつ安定にマージソートする (O(nlgn))
    マージソートの過程で転倒数をメモして返す

    Args:
        L (list)
        begin, end (int)
    
    Returns:
        inv (int): 転倒数
        sorted_list (list): ソート済み
    
    Examples:
        >>> modified_merge_sort([3, 5, 2, 1, 0], 0, 5)
        (9, [0, 1, 2, 3, 5])
    """
    if end - begin == 1:
        return 0, [L[begin]]
    mid = (begin + end) // 2
    left_inv_cnt, left = modified_merge_sort(L, begin, mid)
    right_inv_cnt, right = modified_merge_sort(L, mid, end)
    merge_inv_cnt, sorted_list = _modified_merge(left, right)
    return left_inv_cnt + right_inv_cnt + merge_inv_cnt, sorted_list



# verified @AOJ ALDS1_5_D
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_5_D&lang=ja
def count_inversion(L):
    """
    modified_merge_sort() を用いて L の要素の転倒数を求める (O(nlgn))

    Examples:
        >>> count_inversion([1, 9, 2, 7, 5, 6, 4, 8, 3, 0])
        26
    """
    cnt, _ = modified_merge_sort(L, 0, len(L))
    return cnt



if __name__ == "__main__":
    n = int(input())
    L = list(map(int, input().split()))
    num, seq = modified_merge_sort(L, 0, n)
    print(*seq, sep=' ')
    print(num)

Submission status: Accepted

Solution code:
n = int(input())
s = list(map(int, input().split()))
cnt = 0

def merge(A, left, mid, right):
    L = A[left:mid]
    R = A[mid:right]
    L.append(float('inf'))
    R.append(float('inf'))
    
    i = 0
    j = 0
    global cnt
    for k in range(left, right):
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
            
def mergeSort(A, left, right):
    if left+1 < right:
        mid = (left+right) // 2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
        
mergeSort(s, 0, n)
print(' '.join(map(str, s)))
print(cnt)

Submission status: Accepted

Solution code:
cnt = 0
def merge(A, left, mid, right):
    global cnt
    L = A[left:mid]
    R = A[mid:right]
    L.append(float("inf"))
    R.append(float("inf"))
    i, j = 0, 0
    for k in range(left, right):
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1


def mergeSort(A, left, right):
    if left + 1 < right:
        mid = (left+right)//2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)

def solve(A):
    left = 0
    right = len(A)
    mergeSort(A, left, right)

def resolve():
    n = int(input())
    A = [int(i) for i in input().split()]
    solve(A)
    print(*A)
    print(cnt)

resolve()

Submission status: Accepted

Solution code:
def merge(cnt, A, left, mid, right):
    L = A[left:mid] + [1e+99]
    R = A[mid:right] + [1e+99]
    i = 0
    j = 0
    for k in range(left, right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    cnt.append(right - left)

            
def mergeSort(cnt, A, left, right):
    if left+1 < right:
        mid = (left + right) // 2
        mergeSort(cnt, A, left, mid)
        mergeSort(cnt, A, mid, right)
        merge(cnt, A, left, mid, right)
        
        
import sys
def input():
    return sys.stdin.readline()[:-1]
    
n = int(input())
S = list(map(int, input().split()))

from collections import deque
cnt = deque()
mergeSort(cnt,S,0,n)

print(*S)
print(sum(cnt))

Submission status: Accepted

Solution code:
def merge(A, n ,left, mid, right):
    cnt = 0
    L = A[left:mid] + [float("inf")]
    R = A[mid:right] + [float("inf")]
    i, j = 0, 0
    for k in range(left, right):
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    return cnt

def mergeSort(A, n, left, right):
    if left+1 < right:
        mid = (left + right)//2
        return mergeSort(A, n, left, mid) + mergeSort(A, n, mid, right)\
        + merge(A, n, left, mid, right)    
    return 0

n = int(input())

A = list(map(int, input().split()))

cnt = mergeSort(A, n, 0, n)

print(*A)
print(cnt)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    n = I()
    S = LI()

    cnt = [0]

    def merge(A, left, mid, right):
        L = A[left:mid]
        R = A[mid:right]
        L.append(INF)
        R.append(INF)
        i = 0
        j = 0
        for k in range(left, right):
            if L[i] <= R[j]:
                A[k] = L[i]
                i += 1
            else:
                A[k] = R[j]
                j += 1
            cnt[0] += 1

    def mergeSort(A, left, right):
        if left+1 < right:
            mid = (left+right)//2
            mergeSort(A, left, mid)
            mergeSort(A, mid, right)
            merge(A, left, mid, right)

    mergeSort(S, 0, n)
    print(*S)
    print(cnt[0])

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
# coding: utf-8
# マージソート
INFTY = int(1E20)
count = 0


def merge(A, left, mid, right):
    global INFTY
    global count

    L = [i for i in A[left:mid]]
    R = [i for i in A[mid:right]]

    L.append(INFTY)
    R.append(INFTY)

    idx_L = 0
    idx_R = 0
    for idx in range(left, right):
        count += 1
        if L[idx_L] <= R[idx_R]:
            A[idx] = L[idx_L]
            idx_L += 1
        else:
            A[idx] = R[idx_R]
            idx_R += 1


def mergeSort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
    else:
        return


if __name__ == "__main__":
    n = int(input())
    A = [int(i) for i in input().split()]

    mergeSort(A, 0, n)

    print(' '.join([str(i) for i in A]))

    print(count)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
MAX = 500000
SENTINEL = 2000000000
L = [0]*(MAX//2 + 2)
R = [0]*(MAX//2 + 2)
cnt = 0

def Merge(A,n,left,mid,right,cnt):
    n1 = mid - left
    n2 = right - mid
    for i in range(n1):
        L[i] = A[left + i]
    for i in range(n2):
        R[i] = A[mid + i]
    L[n1] = SENTINEL
    R[n2] = SENTINEL
    L_i = 0
    R_i = 0
    for k in range(left,right):
        cnt += 1
        if L[L_i] <= R[R_i]:
            A[k] = L[L_i]
            L_i += 1
        else:
            A[k] = R[R_i]
            R_i += 1
    return cnt

def MergeSort(A,n,left,right,cnt):
    if left + 1 < right:
        mid = (left + right)//2
        cnt = MergeSort(A,n,left,mid,cnt)
        cnt = MergeSort(A,n,mid,right,cnt)
        cnt = Merge(A,n,left,mid,right,cnt)
    return cnt

if __name__ == "__main__":
    n = int(input())
    array = list(map(int,input().split()))
    cnt = 0
    SENTINEL = 2*10**9
    cnt = MergeSort(array,n,0,n,cnt)
    print(" ".join(map(str,array)))
    print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
nums=list(map(int,input().split()))
count=0
def merge(nums,left,mid,right):
    global count
    inf=10**9
    L=nums[left:mid]+[inf]
    R=nums[mid:right]+[inf]
    i=0
    j=0
    for k in range(left,right):
        count+=1
        if R[j]>=L[i]:
            nums[k]=L[i]
            i+=1

        else:
            nums[k]=R[j]
            j+=1

def merge_sort(nums,left,right):
    if left+1<right:
        mid=(right+left)//2
        merge_sort(nums,left,mid)
        merge_sort(nums,mid,right)
        merge(nums,left,mid,right)

merge_sort(nums,0,n)

def show(nums):
    l=len(nums)
    for i in range(l):
        if i!=l-1:
            print(nums[i],end=" ")
            
        else:
            print(nums[i])
            
show(nums)
print(count)

Submission status: Accepted

Solution code:
def merge(A,left,mid,right):
    global cnt
    n1 = mid - left
    n2 = right - mid
    cnt += n1+n2
    L = [A[left+i] for i in range(n1)]
    R = [A[mid+i] for i in range(n2)]
    L.append(float("inf"))
    R.append(float("inf"))
    i = 0
    j = 0
    for k in range(left,right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1

def mergesort(A,left,right):
    if left +1 < right:
        mid = int((left+right)/2)
        mergesort(A,left,mid)
        mergesort(A,mid,right)
        merge(A,left,mid,right)

n = int(input())
A = list(map(int,input().split()))
cnt = 0
mergesort(A,0,n)
print(" ".join(map(str,A)))
print(cnt)

Submission status: Accepted

Solution code:
#INF = 10**9 + 1
def merge(A, left, mid, right):
    global count
    L = [A[i] for i in range(left, mid)] + [10**9 + 1]
    R = [A[i] for i in range(mid, right)] + [10**9 + 1]
    i,j = 0,0
    for k in range(left, right):
        count += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    
def mergeSort(A, left, right):
    if left + 1 < right:
        mid = int((left + right) / 2)
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)

count = 0
n = int(input())
S = list(map(int,input().split()))
mergeSort(S, 0, n)
print(*S)
print(count)

Submission status: Accepted

Solution code:
from array import array

def readinput():
    n=int(input())
    a=array('L',list(map(int,input().split())))
    return n,a

count=0
def merge(a,left,mid,right):
    INFTY=10**9+1
    global count
    n1=mid-left
    n2=right-mid
    #L=[a[left+i] for i in range(n1)]
    L=a[left:mid]
    L.append(INFTY)

    #R=[a[mid+i] for i in range(n2)]
    R=a[mid:right]
    R.append(INFTY)

    i=0;j=0
    for k in range(left,right):
        if(L[i]<=R[j]):
            a[k]=L[i]
            i+=1
        else:
            a[k]=R[j]
            j+=1
        count+=1
   

def mergeSort(a,left,right):
    if(left+1<right):
        mid=(left+right)//2
        mergeSort(a,left,mid)
        mergeSort(a,mid,right)
        merge(a,left,mid,right)
    return

def main(n,a):
    global count
    mergeSort(a,0,n)
    return a,count

if __name__=='__main__':
    n,a=readinput()
    a,count=main(n,a)
    print(' '.join(map(str,a)))
    print(count)

Submission status: Accepted

Solution code:
import math
def merge(a, left, mid, right):
    global c
    n1 = mid - left
    n2 = right - mid
    l = a[left:left + n1] 
    r = a[mid:mid + n2]
    l.append(10e10)
    r.append(10e10)
    i = 0
    j = 0
    for k in range(left, right):
        c += 1
        if l[i] < r[j]:
            a[k] = l[i]
            i += 1
        else:
            a[k] = r[j]
            j += 1

def mergeSort(a, left, right):
    if left + 1 < right:
        mid = math.ceil((left + right) / 2)
        mergeSort(a, left, mid)
        mergeSort(a, mid, right)
        merge(a, left, mid, right)

n = int(input())
a = list(map(int,input().split()))
c = 0
mergeSort(a, 0, n)
print(" ".join(map(str, a)))
print(c)

Submission status: Accepted

Solution code:
import math
def merge(a, left, mid, right):
    global c
    n1 = mid - left
    n2 = right - mid
    l = a[left:left + n1]
    r = a[mid:mid + n2]
    l.append(10e10) #กำหนดขนาดจำนวนข้อมูล
    r.append(10e10)
    i = 0
    j = 0
    for k in range(left, right):
        c += 1
        if l[i] < r[j]:
            a[k] = l[i]
            i += 1
        else:
            a[k] = r[j]
            j += 1
    #แบ่งครึ่งข้อมูลไปเรื่อยๆจนสุด โดยถ้าจำนวนข้อมูลเป็นจำนวนคี่ ก็ให้แบ่งครึ่งด้านซ้ายมากกว่าด้านขวาเสมอ
def mergeSort(a, left, right):
    if left + 1 < right:
        mid = math.ceil((left + right) / 2)
        mergeSort(a, left, mid)
        mergeSort(a, mid, right)
    #ทำการ merge sort
        merge(a, left, mid, right)

    #รับ input
n = int(input())
a = list(map(int,input().split()))
c = 0
    #เรียก fn
mergeSort(a, 0, n)
    #แสดงผล
print(" ".join(map(str, a)))
print(c)

Submission status: Accepted

Solution code:
n = int(input())
S = [int(i) for i in input().split()]
infty = 10**10
cnt = 0
def merge(A, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    
#     L = [0] * (n1 + 1)
#     R = [0] * (n2 + 1)
#     for i in range(n1):
#         L[i] = A[left + i]
#     for i in range(n2):
#         R[i] = A[mid + i]
# #     L = [A[left + i] for i in range(n1)]
# #     R = [A[mid + i] for i in range(n2)]

#     L[n1] = infty 
#     R[n2] = infty
    
    L = A[left:mid] + [infty]
    R = A[mid:right] + [infty]

    
    i = 0
    j = 0
    for k in range(left, right):
        global cnt
        cnt += 1
        if(L[i] <= R[j]):
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
            
def mergeSort(A, left, right):
    if (left + 1 < right):
        mid = int((left + right)/2)
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
mergeSort(S, 0, len(S))
print(" ".join([str(st) for st in S]))
print(cnt)

Submission status: Accepted

Solution code:
num = int(input())
s = list(map(int, input().split()))
cnt = 0

def merge(A, left, mid, right):
    global cnt
    
    L = A[left:mid] + [10**9 + 1]
    R = A[mid:right] + [10**9 + 1]
    i = 0
    j = 0
    for k in range(left, right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    cnt += right - left

def merge_sort(A, left, right):
    if (left + 1) < right:
        mid = (left + right) // 2
        merge_sort(A, left, mid)
        merge_sort(A, mid, right)
        merge(A, left, mid, right)


merge_sort(s, 0, num)

print(*s)
print(cnt)

Submission status: Accepted

Solution code:
def merge(A, left, mid, right, cnt):
    n1 = mid - left
    n2 = right - mid
    L = [A[left+i] for i in range(n1)]
    R = [A[mid+i] for i in range(n2)]

    L.append(1e10)
    R.append(1e10)

    i = 0 
    j = 0
    c = 0
    for k in range(left, right):
        c += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1 
        else:
            A[k] = R[j]
            j += 1

    else:
        cnt.append(c)


def mergeSort(A, left, right, cnt):
    if left+1 < right:
        mid = (left+right) // 2
        mergeSort(A, left, mid, cnt)
        mergeSort(A, mid, right, cnt)
        merge(A, left, mid, right, cnt)


def main():
    cnt = []
    _ = int(input())
    S = list(map(int, input().split()))
    mergeSort(S, 0, len(S), cnt)
    print(*S)
    print(sum(cnt))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math

n = int(input())
A = list(map(int, input().split()))
cnt = 0
inf = 10**9



def merge(A,left,mid,right):
	global cnt
	L = A[left:mid] + [inf]
	R = A[mid:right] + [inf]
	i = 0
	j = 0

	for k in range(left,right):
		cnt += 1
		if L[i] <= R[j]:
			A[k] = L[i]
			i += 1
		else:
			A[k] = R[j]
			j += 1


def mergeSort(A,left,right):
	if left + 1 < right:
		mid = (left + right) // 2
		mergeSort(A,left,mid)
		mergeSort(A,mid,right)
		merge(A,left,mid,right)

mergeSort(A,0,n)
print(*A)
print(cnt)

Submission status: Accepted

Solution code:
import math
count = 0
def merge(a,left,mid,right):
    global count
    # n1 = mid-left
    # n2 = right - mid
    L = A[left:mid]+[1e9]#[0]*(n1+1)
    R = A[mid:right]+[1e9]#[0]*(n2+1)
    # for i in range(n1):
        # L[i] = A[left+i]
    # for i in range(n2):
        # R[i] = A[mid+i]
    # L[n1] = 1e9
    # R[n2] = 1e9
    i, j = [0,0]
    for k in range(left,right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i+=1
        else:
            A[k] = R[j]
            j+=1
        count+=1
        
def mergesort(A,l,r):
    if (l+1) < r:
        mid = math.floor((l+r)/2)
        mergesort(A,l,mid)
        mergesort(A,mid,r)
        merge(A,l,mid,r)
N = int(input())
A = [int(x) for x in input().split(" ")]
A.append(1e9)
mergesort(A,0,N)
for i in range(len(A)):
    if i < len(A)-2:
        print(A[i],end=" ")
    else:
        print(A[i])
        break

print(count)

Submission status: Accepted

Solution code:
import sys
n = int(input())
sort_list = list(map(int,input().split()))

cnt = []
def merge(A, left,mid,right):
    n1 = mid -left
    n2 = right - mid
    L = [i for i in A[left : left + n1]]
    R = [i for i in A[mid : mid + n2]]
    L.append(sys.maxsize)
    R.append(sys.maxsize)

    i = 0
    j = 0
    c = 0
    for k in range(left,right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1
        c += 1

    cnt.append(c)

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

mergesort(sort_list, 0, len(sort_list))
print(' '.join([str(i) for i in sort_list]))
print(sum(cnt))

Submission status: Accepted

Solution code:
cnt = 0
n = int(input())
S = list(map(int, input().split()))

def mergeSort(S, left, right):
  if left+1 < right:
    mid = (left + right) // 2
    mergeSort(S, left, mid)
    mergeSort(S, mid, right)
    merge(S, left, mid, right)

def merge(S, left, mid, right):

  L = S[left:mid] + [10**10]
  R = S[mid:right] + [10**10]

  i,j = 0,0

  global cnt
  for k in range(left, right):
    cnt += 1
    if L[i] <= R[j]:
      S[k] = L[i]
      i += 1
    else:
      S[k] = R[j]
      j += 1

mergeSort(S, 0, len(S))
print (' '.join(map(str,S)))
print (cnt)

Submission status: Accepted

Solution code:
import sys
from sys import stdin
input = stdin.readline

cnt = 0
INF = 10000000000

def merge(A, left, mid,  right):
  global cnt
  L = A[left:mid] + [INF]
  R = A[mid:right] + [INF]
  i = 0
  j = 0
  for k  in range(left , right):
    if L[i] <= R[j]:
      A[k] = L[i]
      i = i + 1
      cnt += 1
    else:
      A[k] = R[j]
      j = j + 1
      cnt += 1

def mergeSort(A, left, right):
  if left+1 < right:
    mid = (left + right)//2
    mergeSort(A, left, mid)
    mergeSort(A, mid, right)
    merge(A, left, mid, right)

n = int(input())
A =[int(x) for x in input().split()]
mergeSort(A, 0, n)

print(*A)
print(cnt)

Submission status: Accepted

Solution code:
def merge(A, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = A[left:mid]
    R = A[mid:right]
    L.append(10 ** 9)
    R.append(10 ** 9)
    i = 0
    j = 0
    global count
    for k in range(left, right):
        count += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1

def mergeSort(A, left, right):
    if left + 1 < right:
        mid = int((left + right)/2)
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)

n = int(input())
A = list(map(int, input().split()))
count = 0
mergeSort(A, 0, n)

print(*A)
print(count)

Submission status: Accepted

Solution code:
count = [0]

def merge(A, left, right, mid, count):
    lstl = A[left: mid] + [5000000000]
    lstr = A[mid: right] + [5000000000]
    pl = 0
    pr = 0
    for _ in range(left, right):
        if lstl[pl] < lstr[pr]:
            A[left + pl + pr] = lstl[pl]
            pl += 1
            count[0] += 1
        else:
            A[left + pr + pl] = lstr[pr]
            pr += 1
            count[0] += 1
    
    

def merge_sort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        merge_sort(A, left, mid)
        merge_sort(A, mid, right)
        merge(A, left, right, mid, count)

import sys
input = sys.stdin.readline

n = int(input())
S = list(map(int, input().split()))

merge_sort(S, 0, n)
print(" ".join(map(str, S)))
print(count[0])

Submission status: Accepted

Solution code:
count = 0

def merge(array, left, mid, right):
  global count

  n1 = int(mid - left)
  n2 = int(right - mid)

  l = array[left:mid]
  r = array[mid:right]
  
  l.append(9999999999)
  r.append(9999999999)

  i, j = 0, 0

  for k in range(left, right):
    count += 1
    if l[i] <= r[j]:
      array[k] = l[i]
      i += 1
    else:
      array[k] = r[j]
      j += 1

def mergeSort(array, left, right):
  if left + 1 < right:
    mid = int((left + right) / 2)
    mergeSort(array, left, mid)
    mergeSort(array, mid, right)
    merge(array, left, mid, right)

n = int(input())
array = [int(i) for i in input().split()]
mergeSort(array, 0, n)
print(*array)
print(count)

Submission status: Accepted

Solution code:
def merge(A, left, mid, right):
    global c
    n1 = mid - left
    n2 = right - mid
    L = [0 for e in range(n1+1)]
    R = [0 for e in range(n2+1)]
    L = A[left:mid] + [10 ** 9]
    R = A[mid:right] + [10 ** 9]
    i = 0
    j = 0
    for k in range(left,right):
        if L[i] <= R[j]:
          A[k] = L[i]
          i = i + 1
        else:
          A[k] = R[j]
          j = j + 1
    c += right - left

def mergeSort(A, left, right):
    if left+1 < right:
        mid = (left + right)//2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)

if __name__ == "__main__":
    n = int(input())
    S = [int(e) for e in input().split()]
    c = 0
    mergeSort(S,0,n)
    print(*S)
    print(c)

Submission status: Accepted

Solution code:
def merge(A, left, mid, right):
	global cnt

	L = A[left:mid] + [1000000001]
	R = A[mid:right] + [1000000001]

	i = j = 0
	for k in range(left, right):
		if L[i] <= R[j]:
			A[k] = L[i]
			i += 1
		else:
			A[k] = R[j]
			j += 1
	cnt += right - left

def mergeSort(A, left, right):
	if left + 1 < right:
		mid = (left + right) // 2
		mergeSort(A, left, mid)
		mergeSort(A, mid, right)
		merge(A, left, mid, right)

if __name__ == '__main__':
	n = int(input())
	A = list(map(int, input().split()))
	cnt = 0
	mergeSort(A, 0, n)
	print(*A)
	print(cnt)

Submission status: Accepted

Solution code:
import math

def merge(A, left, mid, right, cnt):
    n1 = mid - left
    n2 = right - mid
    L = [0]*(n1+1)
    R = [0]*(n2+1)
    for i in range(n1):
        L[i] = A[left + i]
    for i in range(n2):
        R[i] = A[mid + i]
    L[n1] = math.inf
    R[n2] = math.inf
    i = 0
    j = 0
    for k in range(left,right):
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else: 
            A[k] = R[j]
            j += 1
            
    return A, cnt

def mergeSort(A, left, right, cnt):
    if left+1 < right:
        mid = (left + right)//2
        A, cnt = mergeSort(A, left, mid, cnt)
        A, cnt = mergeSort(A, mid, right, cnt)
        A, cnt = merge(A, left, mid, right, cnt)
    return A, cnt
        
n = int(input())
S = list(map(int,input().split()))

S_out, cnt_out = mergeSort(S,0,len(S),0)

S_str = list(map(str,S))
print(" ".join(S_str))
print(str(cnt_out))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
INF = 10000000000

def merge(A, left, mid, right):
    global ctr

    L = A[left:mid] + [INF]
    R = A[mid:right] + [INF]
    i,j = 0,0
    for k in range(left,right):
        ctr += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1

def mergeSort(A, left, right):
    if left+1 < right:
        mid = (left + right) // 2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
        

n = int(input())
A = list(map(int,input().split()))
ctr = 0

mergeSort(A,0,n)

print(*A)
print(ctr)

Submission status: Accepted

Solution code:
cnt = 0
INF = pow(10, 18)

def merge(A, left, mid, right):
    L = A[left:mid] + [INF]
    R = A[mid:right] + [INF]
    i = 0
    j = 0
    for k in range(left, right):
        global cnt
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1

def mergeSort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)

n = int(input())
s = list(map(int, input().split()))
mergeSort(s, 0, n)
print(*s)
print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
num_list=list(map(int,input().split(" ")))
MAX=500000
L=[None]*((MAX)//2+2)
R=[None]*((MAX)//2+2)
def merge(A,left,mid,right):
    cnt=0
    n1=mid-left
    n2=right-mid


    for i in range(n1):
        L[i]=A[i+left]
    for i in range(n2):
        R[i]=A[i+mid]
    L[n1]=(10**9+1)
    R[n2]=(10**9+1)
    j,k=0,0
    for i in range(left,right):
        cnt+=1
        if L[j]<=R[k]:
            A[i]=L[j]
            j+=1
        else:
            A[i]=R[k]
            k+=1
    return cnt
def mergesort(A,left,right):
    if left+1<right:
        mid=(left+right)//2
        cntL=mergesort(A,left,mid)
        cntR=mergesort(A,mid,right)
        return merge(A,left,mid,right)+cntL+cntR
    return 0
cnt=mergesort(num_list,0,N)
print(*num_list)
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
A=tuple(map(int, input().split()))
cnt=0

def merge_sort(A,cnt):
    m=len(A)
    if m == 1:
        return A,cnt
    else:
        mid=(m+1)//2
        A1=tuple(A[:mid])
        A2=tuple(A[mid:])
        A1,cnt=merge_sort(A1,cnt)
        A2,cnt=merge_sort(A2,cnt)
        n1=len(A1)
        n2=len(A2)
        i1=0
        i2=0
        ans=[0]*(n1+n2)
        j=0
        while j < n1+n2:
            if i1 == n1:
                ans[j]=A2[i2]
                i2+=1
                cnt+=1
            elif i2 == n2:
                ans[j]=A1[i1]
                i1+=1
                cnt+=1
            elif A1[i1] < A2[i2]:
                ans[j]=A1[i1]
                i1+=1
                cnt+=1
            else:
                ans[j]=A2[i2]
                i2+=1
                cnt+=1
            j += 1
        return ans,cnt

sorted_A,cnt=merge_sort(A,0)
print(*sorted_A)
print(cnt)

Submission status: Accepted

Solution code:
# def merge(arr, l, mid, r):
#     L = [arr[i] for i in range(l, mid)]
#     R = [arr[i] for i in range(mid, r)]
#     L.append(int(1e9 + 10))
#     R.append(int(1e9 + 10))
#     i, j = 0, 0
#     cnt = 0
#     for k in range(l, r):
#         if L[i] <= R[j]:
#             arr[k] = L[i]
#             i += 1
#         else:
#             arr[k] = R[j]
#             j += 1
#         cnt += 1
#     return cnt

# def mergeSort(arr, l, r):
#     cnt = 0
#     if l + 1 < r:
#         mid = (l + r) >> 1
#         cnt += mergeSort(arr, l, mid)
#         cnt += mergeSort(arr, mid, r)
#         cnt += merge(arr, l, mid, r)
#     return cnt

# triky

def count(l, r):
    cnt = 0
    if l + 1 < r:
        mid = (l + r) >> 1
        cnt += count(l, mid)
        cnt += count(mid, r)
        cnt += r - l
    return cnt

cnt = count(0, int(input()))
arr = list(map(int, input().split()))
arr.sort()
print(*arr)
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
S = [int(s) for s in input().split()]

snt = 10 ** 9 + 1
cnt = 0

# L, R = [0] * 500000, [0] * 500000

def merge(S, N, left, mid, right):
    global cnt
    # N1 = mid - left
    # N2 = right - mid
    # for i in range(N1):
    #     L[i] = S[left + i]
    # for i in range(N2):
    #     R[i] = S[mid + i]
    # L[N1] = R[N2] = snt
    L = S[left:mid] + [snt]
    R = S[mid:right] + [snt]
    i, j = 0, 0
    for k in range(left, right):
        cnt += 1
        if L[i] <= R[j]:
            S[k] = L[i]
            i += 1
        else:
            S[k] = R[j]
            j += 1

def merge_sort(S, N, left, right):
    if left + 1 < right:
        mid = int((left + right) / 2)
        merge_sort(S, N, left, mid)
        merge_sort(S, N, mid, right)
        merge(S, N, left, mid, right)

merge_sort(S, N, 0, N)

print(*S)
print(cnt)