N = int(input())
method = int(input())
name = []
score = []
dic = {}
for i in range(N):
x1, x2 = input().split()
name.append(x1)
score.append(int(x2))
# 冒泡排序
def st(score, method, name):
L = len(score)
for i in range(L-1):
for j in range(L-1-i):
if method == 1: # 升序
if score[j] > score[j+1]:
y = score[j]
score[j] = score[j+1]
score[j+1] = y
z = name[j]
name[j] = name[j+1]
name[j+1] = z
else:
if score[j] < score[j+1]:
y = score[j]
score[j] = score[j+1]
score[j+1] = y
z = name[j]
name[j] = name[j+1]
name[j+1] = z
return
st(score, method, name)
for i in range(N):
print(name[i] + ' ' + str(score[i]))