#include <iostream>
#include <algorithm>
using namespace std;
struct stu {//自定义结构体
    string name;
    int grade;
};
int descendCmp(stu a, stu b) {
    //注意,ab等值时不交换,在cmp返回时要去除==判断,否则报错
    //此时如果两个元素相等,则都返回false -> 相当于不用交换
    return a.grade > b.grade;
}
int ascendCmp(stu a, stu b) {
    return a.grade < b.grade;
}
int main() {
    int n, flag;
    while (cin >> n >> flag) {
        stu* student = new stu[n];
        for (int i = 0; i < n; i++) {
            cin >> student[i].name >> student[i].grade;
        }
        switch (flag) {
            case 0:
				//stable_sort()使用归并,是稳定的;sort()使用快排,不满足稳定要求
                stable_sort(student, student + n, descendCmp); break;
            case 1:
                stable_sort(student, student + n, ascendCmp); break;
            default: break;
        }
        for (int i = 0; i < n; i++) {
            cout << student[i].name << " " << student[i].grade<<endl;
        }
        delete []student;
    }
    return 0;
}