while True:
    try:
        arr = []
        cnt = int(input())
        flag = int(input())
        px_flag = True
        if flag == 1:
            px_flag = False
        for i in range(cnt):
            name, score = map(str, input().split())
            arr.append([name,int(score)])
        # print(arr) # [['fang', 90], ['yang', 50], ['ning', 70]]
        px = sorted(arr, key=lambda x:x[1], reverse = px_flag)
        # print(px)  # [['yang', 50], ['ning', 70], ['fang', 90]]
        for i in px:
            j = i[0] + ' ' + str(i[1])
            print(j)

    except:
        break