# 0是降序,1是升序
#此题易错点:保证排序的稳定性
#一开始单纯先排序后reverse(),这样是不稳定的,应该在使用sorted时,就选择置reverse参数为False或True
while True:
    try:
        n = int(input())
        x = input()
        stu = [x for x in range(n)]
        if x == "1":
            for i in range(n):
                stu[i] = input().split(" ")
            for j in range(n):
                stu[j][1] = int(stu[j][1])
            stu = sorted(stu, key=lambda s: s[1])
            for k in range(n):
                print(stu[k][0], end=" ")
                print(stu[k][1])
        if x == "0":
            for i in range(n):
                stu[i] = input().split(" ")
            for j in range(n):
                stu[j][1] = int(stu[j][1])
            stu = sorted(stu, key=lambda s: s[1], reverse=True)
            for k in range(n):
                print(stu[k][0], end=" ")
                print(stu[k][1])
    except:
        break