#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;

struct student{
    string name;
    int score;
    student(string n,int s):name(n),score(s){}
};

bool compare0(student s1,student s2){
    return s1.score>s2.score;
}
bool compare1(student s1,student s2){
    return s1.score<s2.score;
}

int main(){
    vector<student> list;
    string name;
    int n,flag,s;
    while (cin>>n>>flag){
        for (int i = 0; i < n; ++i) {
            cin>>name>>s;
            list.push_back(student(name,s));
        }
        if (flag){
            stable_sort(list.begin(),list.end(), compare1);
        } else{
            stable_sort(list.begin(),list.end(), compare0);
        }
        for (int i = 0; i < n; ++i) {
            cout<<list[i].name<<" "<<list[i].score<<endl;
        }
    }

    return 0;
}