Problem:


Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4     do if A[j] n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card  ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1



Sample input:
6
D 3
H 2
D 1
S 3
D 2
C 1


Sample output:
Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Submission status: Accepted

Solution code:
import copy

def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

def correct_same_num_suits(l, num, first, ele_cnt):
    suits = []
    append_cnt = 0
    for i in range(first, N):
        if num == l[i][1]:
            suits.append(l[i][0])
            append_cnt += 1
        if ele_cnt == append_cnt:
            break
    return suits

def is_stable():
    idx = 0
    while idx < N-1:
        idx_incr_flg = True
        if A[idx][1] == A[idx+1][1]:
            num = A[idx][1]
            j = idx
            ele_cnt = 0
            while j < N and num == A[j][1]:
                ele_cnt += 1
                j += 1
            sorted_suits = correct_same_num_suits(A, num, idx, ele_cnt)
            orig_suits = correct_same_num_suits(orig_list, num, 0, ele_cnt)
            if sorted_suits != orig_suits:
                return False
            idx += len(sorted_suits)
            idx_incr_flg = False
        if idx_incr_flg:
            idx += 1
    return True


N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
orig_list = copy.deepcopy(A)

quick_sort(0, N-1)

is_stable = is_stable()
if is_stable:
    print("Stable")
else:
    print("Not stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
import copy

def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

def is_stable():
    for i in range(N-1):
        if A[i][1] == A[i+1][1]:
            small_idx, large_idx = 0, 0
            for j in range(N):
                if A[i] == orig_list[j]:
                    small_idx = j
                elif A[i+1] == orig_list[j]:
                    large_idx = j
            if small_idx > large_idx:
                return False
    return True


N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
orig_list = copy.copy(A)

quick_sort(0, N-1)

is_stable = is_stable()
if is_stable:
    print("Stable")
else:
    print("Not stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
import copy

def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

def is_stable():
    for i in range(N-1):
        if A[i][1] == A[i+1][1]:
            small_idx, large_idx = 0, 0
            cnt = 0
            for j in range(N):
                if A[i] == orig_list[j]:
                    small_idx = j
                    cnt += 1
                elif A[i+1] == orig_list[j]:
                    large_idx = j
                    cnt += 1
                if cnt == 2:
                    break
            if small_idx > large_idx:
                return False
    return True


N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
orig_list = copy.copy(A)

quick_sort(0, N-1)

is_stable = is_stable()
if is_stable:
    print("Stable")
else:
    print("Not stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

def is_stable():
    for i in range(N-1):
        if A[i][1] == A[i+1][1]:
            small_idx, large_idx = 0, 0
            cnt = 0
            for j in range(N):
                if A[i] == orig_list[j]:
                    small_idx = j
                    cnt += 1
                elif A[i+1] == orig_list[j]:
                    large_idx = j
                    cnt += 1
                if cnt == 2:
                    break
            if small_idx > large_idx:
                return False
    return True


N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
orig_list = A[:]

quick_sort(0, N-1)

is_stable = is_stable()
if is_stable:
    print("Stable")
else:
    print("Not stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

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

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

INFTY = 1000000001

N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
merge_list = A[:]

quick_sort(0, N-1)
merge_sort(0, N)

if A == merge_list:
    print("Stable")
else:
    print("Not stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
def partition(p, r):
    i = p
    for j in range(p, r):
        if A[r][1] >= A[j][1]:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[r], A[i] = A[i], A[r]
    return i

def quick_sort(p, r):
    if p < r:
        q = partition(p, r)
        quick_sort(p, q-1)
        quick_sort(q+1, r)

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

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

INFTY = 1000000001

N = int(input())
A = []
for _ in range(N):
    suit, num = input().split()
    num = int(num)
    A.append([suit, num])
merge_list = A[:]

quick_sort(0, N-1)
merge_sort(0, N)

is_stable = True
for i in range(N):
    if A[i][0] != merge_list[i][0]:
        print("Not stable")
        is_stable = False
        break
if is_stable:
    print("Stable")

for card in A:
    print("%s %d" % (card[0], card[1]))

Submission status: Accepted

Solution code:
import copy

n = int(input())
A = []
for i in range(n):
    tmp = input().split()
    A.append([tmp[0], int(tmp[1])])
B = copy.deepcopy(A)

# ===========================================================================

def partition(A, p, r):
    x = A[r][1]
    i = p - 1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q-1)
        quick_sort(A, q+1, r)

# ============================================================================
# merge sort (for comparison)

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[n1] = ['nan', float("inf")]
    R[n2] = ['nan', float("inf")]
    i = 0
    j = 0
    for k in range(left, right):
        if L[i][1] <= R[j][1]:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 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, mid, right)


# ============================================================================
quick_sort(A, 0, len(A)-1)
merge_sort(B, 0, len(B))

print('Stable' if A == B else 'Not stable')
for x in A:
    print(x[0] + ' ' + str(x[1]))

Submission status: Accepted

Solution code:
def partition(A, p, r):
    x = A[r][1]
    i = p - 1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        # 左半分
        quick_sort(A, p, q - 1)
        # 右半分
        quick_sort(A, q + 1, r)
n = int(input())
A = []
for _ in range(n):
    a, b = input().split()
    A.append((a, int(b)))
ind = dict((e, i) for i, e in enumerate(A))
quick_sort(A, 0, n - 1)
for i in range(n - 1):
    if A[i][1] == A[i + 1][1]:
        if ind[A[i]] > ind[A[i + 1]]:
            print('Not stable')
            break
else:
    print('Stable')
for i in A:
    print(*i)

Submission status: Accepted

Solution code:

def merge(A, n, left, mid, right):
    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] = new_list("X", SENTINEL)
    R[n2] = new_list("X", SENTINEL)
    i = 0
    j = 0
    for k in range(left, right):
        if L[i].value <= R[j].value:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1


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


def partition(p, r):
    x = B[r].value
    i = p - 1  # <xの右端
    for j in range(p, r):
        if B[j].value <= x:
            i += 1
            B_tmp = B[i]
            B[i] = B[j]
            B[j] = B_tmp
    t = B[i+1]
    B[i+1] = B[r]
    B[r] = t
    return i+1


def quickSort(B, n, p, r):
    if p < r:
        q = partition(p, r)
        quickSort(B, n, p, q-1)
        quickSort(B, n, q+1, r)


class new_list:
    def __init__(self, a1, a2):
        self.suit = a1
        self.value = a2


n = int(input())
S_tmp = [input().split() for i in range(n)]
# for i in range(n):
#     print(S_tmp[i])
A = []
B = []
for i in range(n):
    A.append(new_list(S_tmp[i][0], int(S_tmp[i][1])))
    B.append(new_list(S_tmp[i][0], int(S_tmp[i][1])))

# for i in range(n):
#     print(i, A[i].suit, A[i].value)

L = [''] * (n//2+2)
R = [''] * (n//2+2)
SENTINEL = 2000000000
mergeSort(A, n, 0, n)
quickSort(B, n, 0, n-1)

for i in range(n):
    if A[i].suit != B[i].suit:
        break
if i == n-1:
    print("Stable")
else:
    print("Not stable")
for i in range(n):
    print(B[i].suit, B[i].value)

Submission status: Accepted

Solution code:
import sys


def partition_for_second_element(array, first, end):
    criteria = array[end][1]
    i_ins = first
    for i_cur in range(first, end):
        if array[i_cur][1] <= criteria:
            array[i_ins], array[i_cur] = array[i_cur], array[i_ins]     # swap
            i_ins += 1
    array[i_ins], array[end] = array[end], array[i_ins]     # swap
    return i_ins


def quick_sort(array, first, end):
    #print("quick_sort",first,end,array)
    if first < end:
        criteria_idx = partition_for_second_element(array, first, end)
        quick_sort(array, first, criteria_idx - 1)
        quick_sort(array, criteria_idx + 1, end)


def shcd_order(cards):
    orders = {}
    for card in cards:
        if card[1] not in orders:
            orders[card[1]] = [card[0]]
        else:
            orders[card[1]].append(card[0])
    return orders


def is_identical_order(prev_orders, after_orders):
    for key, value in prev_orders.items():
        if after_orders[key] != value:
            return False
    return True


def main():
    input_lines = sys.stdin.readlines()
    n = int(input_lines[0].rstrip())
    cards = [(x.split()[0], int(x.split()[1])) for x in input_lines[1:]]
    prev_orders = shcd_order(cards)
    quick_sort(cards, 0, n-1)
    after_orders = shcd_order(cards)
    if is_identical_order(prev_orders, after_orders):
        print('Stable')
    else:
        print('Not stable')
    [print(x[0], x[1]) for x in cards]
    return


main()

Submission status: Accepted

Solution code:
import copy

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

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



def partition(A, p, r):
    x = A[r][1]
    i = p - 1
    for j in range(p, r):
        if A[j][1] <= x:
            i = i + 1
            A[i], A[j] = A[j], A[i]

    A[i+1], A[r] = A[r], A[i+1]
    return i + 1

def quickSort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q-1)
        quickSort(A, q+1, r)
        
    
n = int(input())
A = [None for i in range(n)]
for i in range(n):
    a, b = input().split()
    A[i] = (a, int(b))

B = copy.deepcopy(A)
quickSort(A, 0, n-1)
mergeSort(B, 0, n)
if A == B:
    print("Stable")
else:
    print("Not stable")

ans = [str(x[0]) +" "+str(x[1]) for x in A]
ans = '\n'.join(ans)
print(ans)

Submission status: Accepted

Solution code:
def InputData():
    
    sequence_len = int(input())
    sequence = [input().split(" ") for _ in range(sequence_len)]
    sequence_m = [(a[0], int(a[1])) for a in sequence]
    sequence_q = [(a[0], int(a[1])) for a in sequence]
    return sequence_len, sequence_m, sequence_q

def partition(sequence, p, r):
    x = sequence[r]
    i = p - 1
    for j in range(p, r):
        if sequence[j][1] <= x[1]:
            i += 1
            sequence[i], sequence[j]= sequence[j], sequence[i]
    
    sequence[i+1], sequence[r] = sequence[r], sequence[i+1]
    return i+1

def quickSort(sequence, p, r):
    if p < r:
        q = partition(sequence, p, r)
        quickSort(sequence, p, q-1)
        quickSort(sequence, q+1, r)

def merge(sequence, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    sequence_left = sequence[left:left + n1]
    sequence_right = sequence[mid:mid + n2]
    sequence_left.append([None, float('inf')])
    sequence_right.append([None, float('inf')])

    left_cnt = 0
    right_cnt = 0
    for i in range(left, right):
        if sequence_left[left_cnt][1] <= sequence_right[right_cnt][1]:
            sequence[i] = sequence_left[left_cnt]
            left_cnt += 1
        else:
            sequence[i] = sequence_right[right_cnt]
            right_cnt += 1

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

def PrintOut(sequence_m, sequence_q):
    if sequence_m == sequence_q:
        print("Stable")
    else:
        print("Not stable")
    
    for a in sequence_q:
        print(a[0], a[1])

def main():
    [sequence_len, sequence_m, sequence_q] = InputData()
    mergeSort(sequence_m, 0, sequence_len)
    quickSort(sequence_q, 0, sequence_len-1)
    
    PrintOut(sequence_m, sequence_q)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
sentinel = str(10**9+1)

def partition(A, p, r):
    x = int(A[r][1])
    i = p - 1
    for j in range(p, r):
        if int(A[j][1]) <= x:
            i = i + 1
            A[i], A[j] = A[j], A[i]

    A[i+1], A[r] = A[r], A[i+1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q-1)
        quick_sort(A, q+1, r)

def merge(lst,left,middle,right):
    left_lst  =  lst[left:middle] + [['',sentinel]]
    right_lst = lst[middle:right] + [['',sentinel]]

    i,j = 0,0
    for k in range(left,right):
        if int(left_lst[i][1]) <= int(right_lst[j][1]):
            lst[k] = left_lst[i]
            i += 1
        else:
            lst[k] = right_lst[j]
            j += 1

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


n = int(input())
n_lst = [[i for i in input().split()] for _ in range(n)]
m_lst = list(n_lst)
quick_sort(n_lst,0,n-1)
merge_sort(m_lst,0,n)
print('Stable' if n_lst == m_lst else 'Not stable')
for ans in n_lst:
    print('{} {}'.format(ans[0],ans[1]))

Submission status: Accepted

Solution code:
n = int(input())
data = list(input().split() for _ in range(n))
c = 0

for k in range(n):
    data[k].append(str(k))


def exchange(a, i, j):
    tmp = a[i]
    a[i] = a[j]
    a[j] = tmp
    return a


def partition(a, p, r):
    x = int(a[r][1])
    i = p-1
    for j in range(p, r):
        if int(a[j][1]) <= x:
            i += 1
            a = exchange(a, i, j)
    exchange(a, i+1, r)
    return i+1


def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q-1)
        quicksort(a, q+1, r)


quicksort(data, 0, n-1)

for l in range(n-1):
    if int(data[l][1]) == int(data[l+1][1]):
        if int(data[l][2]) > int(data[l+1][2]):
            print('Not stable')
            c = 1
            break

if c == 0:
    print('Stable')

for l in range(n):
    print(data[l][0], data[l][1])

Submission status: Accepted

Solution code:
import copy
 
INF = 10000000000
def merge(A, left, mid, right):
    count = 0
    L = A[left:mid] + [(INF,INF)]
    R = A[mid:right] + [(INF,INF)]
     
    i, j = 0, 0
    for k in range(left, right):
        count = count + 1
        if L[i][1] <= R[j][1]:
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1
    return count
 
def mergeSort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        countL = mergeSort(A, left, mid)
        countR = mergeSort(A, mid, right)
        return merge(A, left, mid, right) + countL + countR
    return 0
def partition(a,p,r):
    x=a[r][1]
    i=p-1
    for j in range(p,r):
        if a[j][1]<=x:
            i+=1
            a[i],a[j]=a[j],a[i]
    a[i+1],a[r]=a[r],a[i+1]
    return i+1
def quickSort(a,p,r):
    if p<r:
        q=partition(a,p,r)
        quickSort(a,p,q-1)
        quickSort(a,q+1,r)
n = int(input())
A = [None for i in range(n)]
for i in range(n):
    a, b = input().split()
    A[i] = (a, int(b))

B = copy.deepcopy(A)
quickSort(A, 0, n-1)
mergeSort(B, 0, n)
if A == B:
    print("Stable")
else:
    print("Not stable")
ans = [str(x[0]) +" "+str(x[1]) for x in A]
ans = '\n'.join(ans)
print(ans)

Submission status: Accepted

Solution code:
a = []
b = {}
n = int(input())
for _ in range(n):
    s, i = input().split()
    a += [(s, int(i))]
    b.setdefault(int(i), []).append(s)
b = {val: iter(s).__next__ for val, s in b.items()}

def partition(a, left, right):
    standard = a[right][1]
    cnt = left
    for i in range(left, right):
        if a[i][1] <= standard:
            a[cnt],a[i] = a[i], a[cnt]
            cnt += 1
    a[cnt],a[right] = a[right], a[cnt]
    return cnt

def quickSort(a, left = 0, right = len(a) - 1):
    if 1 <= right - left:
        cnt_ = partition(a, left, right)
        quickSort(a,left, cnt_ - 1)
        quickSort(a,cnt_ + 1, right)

quickSort(a, 0 , len(a)-1)

ok = 1
for s, i in a:
    if b[i]() != s:
        ok = 0
print(['Not stable','Stable'][ok])


for i in range(n):
    print(*a[i])

Submission status: Accepted

Solution code:
from copy import deepcopy

def Partition(A, p, r):
    x = A[r][1]
    i = p-1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i+1

def Quicksort(A, p, r):
    if p < r:
        q = Partition(A, p, r)
        Quicksort(A, p, q-1)
        Quicksort(A, q+1, r)


n = int(input())
cards = []
for i in range(n):
    card = input().split()
    card[1] = int(card[1])
    cards.append(card)
prev_cards = deepcopy(cards)
prev_cards.sort(key=lambda card: card[1])

Quicksort(cards, 0, n-1)

if cards == prev_cards:
    print("Stable")
else:
    print("Not stable")

for card in cards:
    print(' '.join(map(str, card)))

Submission status: Accepted

Solution code:
def q(a,l,r):
    if l>=r:return
    i=l
    for j in range(l,r):
        if int(a[j][2:])<=int(a[r][2:]):
            a[i],a[j]=a[j],a[i]
            i+=1
    a[i],a[r]=a[r],a[i]
    q(a,l,i-1)
    q(a,i+1,r)

n=input()
a=[raw_input() for _ in range(n)]
b=a[:]
q(b,0,len(b)-1)
n=0
print "Stable" if b==sorted(a,key=lambda i:int(i[2:])) else "Not stable"
for i in b:print i

Submission status: Accepted

Solution code:
def partition(a, p, r):
    q  = p
    for i in range(p, r):
        if a[i][1] <= a[r][1]:
            a[q], a[i] = a[i], a[q]
            q += 1
    a[q], a[r] = a[r], a[q]
    return q 
  
def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q-1)
        quicksort(a, q+1, r)
  
def check_stable(a):
    for i in range(1, len(a)):
        if a[i - 1][1] == a[i][1]:
            if a[i - 1][2] > a[i][2]:
                return 'Not stable'
    return 'Stable'
      
import sys
n = int(sys.stdin.readline())
a = []
for i in range(n):
    suit, num = sys.stdin.readline().split()
    a += [[suit, int(num), i]]
  
quicksort(a, 0, len(a) - 1)
print(check_stable(a))
  
for line in a:
    print(line[0],line[1])

Submission status: Accepted

Solution code:
from collections import defaultdict
def partition(A, p, r):
    x = A[r][1]
    i = p - 1
    for j in xrange(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i + 1


def quickSort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q-1)
        quickSort(A, q+1, r)

def getMarkOrder(A):
    d = defaultdict(list)
    for x in A:
        d[x[1]].append(x[0])
    return d

n = int(raw_input())
A = []
for i in xrange(n):
    X = raw_input().split()
    A.append((X[0], int(X[1])))
B = getMarkOrder(A)
quickSort(A, 0, n-1)
C = getMarkOrder(A)
print 'Stable' if B == C else 'Not stable'
for x in A:
    print x[0], x[1]

Submission status: Accepted

Solution code:
def partition(a, p, r):
    x = a[r][1]
    i = p - 1
    for j in range(p, r):
        if a[j][1] <= x:
            i = i + 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[r] = a[r], a[i + 1]
    return i + 1


def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q - 1)
        quicksort(a, q + 1, r)


def checkstable(a):
    for i in range(1, len(a)):
        if a[i - 1][1] == a[i][1]:
            if a[i - 1][2] > a[i][2]:
                return "Not stable"
    return "Stable"


import sys
n = int(input())
a = []
for i in range(n):
    suit, num = sys.stdin.readline().split()
    a += [[suit, int(num), i]]

quicksort(a, 0, len(a) - 1)
print(checkstable(a))

for line in a:
    print(line[0], line[1])

Submission status: Accepted

Solution code:
def partition(a,p,r):
    x = int(a[r][1])
    i = p - 1
    for j in range(p,r):
        if int(a[j][1]) <= x:
            i += 1
            a[i],a[j] = a[j],a[i]
    a[i+1],a[r] = a[r],a[i+1]
    return i + 1
def quicksort(a,p,r):
    if p < r:
        q = partition(a,p,r)
        quicksort(a,p,q-1)
        quicksort(a,q+1,r)
n = input()
a = [map(str, raw_input().split()) for i in range(n)]
b = a[:]
quicksort(a,0,n-1)
print "Stable" if a == sorted(b, key = lambda x: int(x[1])) else "Not stable"
for s,i in a: print s,i

Submission status: Accepted

Solution code:
def partition(A, p, r):
  (suite, x) = A[r]
  i = p - 1
  for j in range(p, r):
    if A[j][1] <= x:
      i = i + 1
      A[i], A[j] = A[j], A[i]
  A[i+1], A[r] = A[r], A[i+1]
  return i + 1

def quick_sort(A, p, r):
  if p < r:
    q = partition(A, p, r)
    quick_sort(A, p, q - 1)
    quick_sort(A, q + 1, r)

if __name__ == "__main__":
  import sys
  n = sys.stdin.readline()
  items = []
  suite_order = {}
  for line in sys.stdin:
    item  = line.strip().split()
    items.append(item)
    if item[1] not in suite_order:
      suite_order[item[1]] = []
    suite_order[item[1]].append(item[0])

  items = [ (item[0], int(item[1])) for item in items ]
  quick_sort(items, 0, len(items) - 1)

  is_stable = True
  for item in items:
    if suite_order[str(item[1])][0] != item[0]:
      is_stable = False
    suite_order[str(item[1])].pop(0)
  if is_stable:
    print "Stable"
  else:
    print "Not stable"

  for item in items:
    print "%s %s" % (item[0], str(item[1]))

Submission status: Accepted

Solution code:
N = int(raw_input())
A, A2 = [], []
for i in range(N):
    a = raw_input().split()
    A.append([a[0], int(a[1])])
    A2.append([a[0], int(a[1])])

def partition(A):
    i = 0
    r = A[-1][1]
    for j in range(0, len(A)):
        if A[j][1] <= r:
            A[i], A[j] = A[j], A[i]
            i += 1
    return i-1, A

def quickSort(A):
    if len(A) < 2:
        return A
    
    q, A = partition(A)
    left = A[:q]
    right = A[q+1:]
    
    A[:q] = quickSort(left)
    A[q+1:] = quickSort(right)
    return A

def merge(left, right):
    global count
    sorted_list = []
    l_index = 0
    r_index = 0

    while l_index < len(left) and r_index < len(right):
        if left[l_index][1] <= right[r_index][1]:
            sorted_list.append(left[l_index])
            l_index += 1
        else:
            sorted_list.append(right[r_index])
            r_index += 1

    if len(left) != l_index:
        sorted_list.extend(left[l_index:])
    if len(right) != r_index:
        sorted_list.extend(right[r_index:])

    return sorted_list 

def mergeSort(A):
    
    if len(A) <= 1:
        return A

    mid = len(A) // 2
    left = A[:mid]
    right = A[mid:]

    left = mergeSort(left)
    right = mergeSort(right)

    return list(merge(left, right))

A = quickSort(A)
if A == mergeSort(A2):
    print "Stable"
else:
    print "Not stable"
for w, i in A:
    print w,i

Submission status: Accepted

Solution code:
def partition(data, left, right):
    pivot = int(data[right][2:])
    i = left - 1
    for j in range(left, right):
        if int(data[j][2:]) <= pivot:
            i += 1
            data[i], data[j] = data[j], data[i]
    data[i+1], data[right] = data[right], data[i+1]
    return i+1

def quick_sort(data, left, right):
    if left < right:
        new_pivot = partition(data, left, right)
        quick_sort(data, left, new_pivot-1)
        quick_sort(data, new_pivot+1, right)

#for comparison
def merge(data, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = data[left : mid]
    R = data[mid : right]
    L.append("  10000000000")
    R.append("  10000000000")
    i = 0
    j = 0
    for k in range(left, right):
        if int(L[i][2:]) <= int(R[j][2:]):
            data[k] = L[i]
            i += 1
        else:
            data[k] = R[j]
            j += 1

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

def main():
    num = raw_input()
    pairs_quick = []
    pairs_check = []
    for i in range(int(num)):
        pair = raw_input()
        pairs_quick.append(pair)
        pairs_check.append(pair)
    
    quick_sort(pairs_quick, 0, int(num)-1)
    merge_sort(pairs_check, 0, int(num))
    if pairs_quick == pairs_check:
        print "Stable"
    else:
        print "Not stable"

    print "\n".join(pairs_quick)
    #print "\n".join(pairs_check)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def partition(data, left, right):
    pivot = int(data[right][2:])
    i = left - 1
    for j in range(left, right):
        if int(data[j][2:]) <= pivot:
            i += 1
            data[i], data[j] = data[j], data[i]
    data[i+1], data[right] = data[right], data[i+1]
    return i+1

def quick_sort(data, left, right):
    if left < right:
        new_pivot = partition(data, left, right)
        quick_sort(data, left, new_pivot-1)
        quick_sort(data, new_pivot+1, right)

def main():
    num = raw_input()
    pairs_quick = []
    pairs_check = []
    for i in range(int(num)):
        pair = raw_input()
        pairs_quick.append(pair)
        pairs_check.append(pair)
    
    quick_sort(pairs_quick, 0, int(num)-1)
    pairs_check = sorted(pairs_check, key = lambda i:int(i[2:]))
    if pairs_quick == pairs_check:
        print "Stable"
    else:
        print "Not stable"

    print "\n".join(pairs_quick)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def partition(a,p,r):
    x=int(a[r][1:])
    i=p-1
    for j in range(p,r):
        if(int(a[j][1:])<=x):
            i+=1
            a[i],a[j]=a[j],a[i]
    a[i+1],a[r]=a[r],a[i+1]
    return i+1

def quicksort(a,p,r):
    if(p<r):
        q=partition(a,p,r)
        quicksort(a,p,q-1)
        quicksort(a,q+1,r)

a=[]
n=int(input())
for i in range(n):
    s=input()
    a.append("".join(s.split()))

c=list(a)
quicksort(c,0,n-1)

d=dict()
i=0
x="-1"
for i in c:
    if(x!=i[1:]):
        d[i[1:]]=[i[:1]]
        x=i[1:]
    else:
        d[x].append(i[:1])

message="Stable"

for i in reversed(a):
    if(i[1:] in d):
        if(d[i[1:]].pop()!=i[:1]):
            message="Not stable"
            break

print(message)

for i in c:
    print("%s %s"%(i[:1],i[1:]))