import java.util.*;

/**
 * HJ68 成绩排序
 */
public class HJ068 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int count = Integer.parseInt(sc.nextLine());//学生个数
            int flag = Integer.parseInt(sc.nextLine());//升序or降序
            Student[] students = new Student[count];
            for (int i = 0; i < count; i++) {
                String[] split = sc.nextLine().split(" ");
                String name = split[0];
                int score = Integer.parseInt(split[1]);
                students[i] = new Student(name, score);
            }
            Arrays.sort(students, (o1, o2) -> {
                if (flag == 1) {
                    return o1.score - o2.score;
                } else {
                    return o2.score - o1.score;
                }
            });
            for (Student student : students) {
                System.out.println(student.name + " " + student.score);
            }
        }
        sc.close();
    }

    public static class Student {
        String name;
        int score;

        Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    }
}