#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;

struct Student{
    string name;
    int score;
};

bool Compare_inc(Student a,Student b){
        return a.score<b.score;
}

bool Compare_dec(Student a,Student b){
        return a.score>b.score;
}

int main() {
    int n, mode;
    while (cin >> n >> mode) { // 注意 while 处理多个 case
        vector<Student> arr(n);
        for(int i=0;i<n;i++){
            cin>>arr[i].name>>arr[i].score;
        }
        if(mode)
            stable_sort(arr.begin(),arr.end(),Compare_inc);
        else
            stable_sort(arr.begin(),arr.end(),Compare_dec);
        for(auto item:arr){
            cout<<item.name<<" "<<item.score<<endl;
        }
    }
    return 0;
}
// 64 位输出请用 printf("%lld")