#include <cstdio>
#include <algorithm>
using namespace std;
struct student{
    char name[100];
    int grade;
    int order;
};
//降序条件
bool comp1(student lsh, student rsh){
    if(lsh.grade<rsh.grade){
        return true;
    }
    else if(lsh.grade==rsh.grade&&lsh.order<rsh.order)
        return true;
    else
        return false;
}
bool comp2(student lsh, student rsh){
    if(lsh.grade>rsh.grade){
        return true;
    }
    else if(lsh.grade==rsh.grade&&lsh.order<rsh.order)
        return true;
    else
        return false;
}
int main(){
    int people;
    int method;
    while(scanf("%d%d",&people,&method)!=EOF){
    student stu[people];
    for(int i=0;i<people;i++){
        scanf("%s%d",&stu[i].name,&stu[i].grade);
        stu[i].order=i;
    }
    if(method==1){
        sort(stu,stu+people,comp1);
    }
    else if(method==0){
        sort(stu, stu + people,comp2);
    }
    for(int i=0;i<people;i++) {
        printf("%s %d\n", stu[i].name,stu[i].grade);
    }
    }
}