#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
struct P{
    string name;
    int score;
} stu[N];
bool cmp_up(P p1, P p2){
    return p1.score < p2.score;
}
bool cmp_down(P p1, P p2){
    return p1.score > p2.score;
}

int main() {
    int n;
    int flag;
    while(cin >> n){
        cin >> flag;
        for(int i = 0; i < n; i ++){
            cin >> stu[i].name >> stu[i].score;
        }
        //重点:sort是不稳定排序,stable_sort才是稳定排序
        if(flag == 0) stable_sort(stu, stu + n, cmp_down);
        else stable_sort(stu, stu + n, cmp_up);
        for(int i = 0; i < n; i ++)
            cout << stu[i].name <<" "<<stu[i].score << endl;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")