#include <stdio.h>
typedef struct score{
    char name[10];
    int score;
} SCORE;

void SelectionSort(SCORE *p,int n,int (*compare)(int a,int b));
int Ascending(int a,int b);
int Descending(int a,int b);

int main() {
    int n,order;
    while((scanf("%d",&n)!=EOF)&&scanf("%d",&order)!=EOF){
        SCORE *p=(SCORE *)malloc(sizeof(SCORE)*n);
        for(int i=0;i<n;i++){
            scanf("%s %d",p[i].name,&p[i].score);
            getchar();
        }
        if(order==1) SelectionSort(p,n,Ascending);
        else SelectionSort(p,n,Descending);
        for(int i=0;i<n;i++){
            printf("%s %d",p[i].name,p[i].score);
            puts("");

        }
    }
    return 0;
}
void SelectionSort(SCORE *p,int n,int (*compare)(int a,int b)){
    SCORE temp;
    for(int i=0;i<n-1;i++){
        for(int j=0;j<n-1;j++){
            if(compare(p[j].score,p[j+1].score)){
                temp=p[j];
                p[j]=p[j+1];
                p[j+1]=temp;
            } 
        }
    }
}
int Ascending(int a,int b){
    return a>b;
}
int Descending(int a,int b){
    return a<b;
}