import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int sort = scanner.nextInt();

        ArrayList<String[]> arrayList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            String name = scanner.next();
            int score = scanner.nextInt();

            String[] strings = new String[2];
            strings[0] = name;
            strings[1] = String.valueOf(score);
            arrayList.add(strings);
        }

        if (sort == 1) {
            arrayList.sort((o1, o2) -> Integer.parseInt(o1[1]) - Integer.parseInt(o2[1]));
        } else {
            arrayList.sort((o1, o2) -> Integer.parseInt(o2[1]) - Integer.parseInt(o1[1]));
        }

        for (String[] strings : arrayList) {
            System.out.println(strings[0] + " " + strings[1]);
        }
    }
}