while True:
    try:
        n, order = int(input()), int(input())
        data = [] # 不能用字典保存,因为可能有名字是重复的
        for _ in range(n):
            name, score = input().split()
            data.append((name, int(score)))
        if order:
            for i in sorted(data, key=lambda x:x[1]): # 升序
                print(i[0], i[1])
        else:
            for i in sorted(data, key=lambda x:x[1], reverse=True): # 降序
                print(i[0], i[1])
    except:
        break