while True:
    try:
        d = {}
        n = int(input())
        method = input()
        for i in range(n):
            name,score = input().split()
            if not int(score) in d:
                d[int(score)] = [name]
            else:
                d[int(score)].append(name)
        reverse = True if method == '0' else False
        for key in sorted(d.keys(),reverse = reverse):
            for i in range(len(d[key])):
                print(d[key][i], key, sep = ' ')
    except:
        break