import sys while True: try: N = int(input()) gz = input() L = [] for i in range(N): L.append(input().split()) if gz == "1": L.sort(key = lambda x: int(x[1])) else: L.sort(key = lambda x: 100 - int(x[1])) for c in L: print(" ".join(c)) except: # print(sys.exc_info()) break