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

struct stu1{//升序
    string name;
    int score;
    int i;//录入先后顺序
    bool operator< (const stu1 &t) const{
        if(t.score==score) return i<t.i;
        else return score<t.score;
    }
};
struct stu0{//降序
    string name;
    int score;
    int i;//录入先后顺序
    bool operator< (const stu0 &t) const{
        if(t.score==score) return i<t.i;
        else return score>t.score;
    }
};
int main() {
    int n;
    while(cin>>n){
        int k;
        cin>>k;
        if(k==1){
            stu1 *a=new stu1[n];
            for(int i=0;i<n;i++) {
                cin>>a[i].name>>a[i].score;
                a[i].i=i;
            }
            sort(a,a+n);
            for(int i=0;i<n;i++) cout<<a[i].name<<" "<<a[i].score<<endl;
        }else{
            stu0 *b=new stu0[n];
            for(int i=0;i<n;i++) {
                cin>>b[i].name>>b[i].score;
                b[i].i=i;
            }
            sort(b,b+n);
            for(int i=0;i<n;i++) cout<<b[i].name<<" "<<b[i].score<<endl;
        }
    }
    return 0;
}