#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define len 1009
#define maxint 1<<31-1

typedef struct student{
    char name[1000];
    int grade;
    int num;
}stu;

stu initial_stu(char name[],int grade,int num){
    stu st;
    strcpy(st.name,name);
    st.grade = grade;
    st.num = num;
    return st;
}

stu stu_list[len];

int flag;

int cmp(const void*s1,const void*s2){
    stu a1 = *(stu*)s1;
    stu a2 = *(stu*)s2;
    if(a1.grade==a2.grade){
        return a1.num-a2.num;
    }
    return flag==1?a1.grade-a2.grade:a2.grade-a1.grade;
}

int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        scanf("%d",&flag);
        char name[1000];
        int grade;
        for(int i = 0;i<n;i++){
            scanf("%s %d",name,&grade);
            stu_list[i] = initial_stu(name,grade,i);
        }
        qsort(stu_list,n,sizeof(stu),cmp);
        for(int i = 0;i<n;i++){
            stu st = stu_list[i];
            printf("%s %d\n",st.name,st.grade);
        }
    }
}