while True:
    try:
        n = int(input())
        p = -1 if input() == '0' else 1
        l1 = []
        for i in range(n):
            s = input().split()
            l1.append((int(s[1]),i,s[0]))
        l1.sort(key=lambda x:(p*x[0],x[1],x[2]))
        for i in l1:
            print(i[2]+' '+str(i[0]))
    except:
        break