#include <iostream>
#include <cstdio>
#include "string"
#include "algorithm" //一般机试都用 库里的 sort,重点调compare交换条件
using namespace std;
typedef struct list {
    char name[10];
    int grade;
    int seq = 0;
} list;
bool compare1(list lhs, list rhs) { //用来升序的comapre
    if (lhs.grade < rhs.grade) {
        return true;
    } else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
        return true;
    else
        return false;

}
bool compare2(list lhs, list rhs) { //用来降序的comapre
    if (lhs.grade > rhs.grade) {
        return true;
    } else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
        return true;
    else
        return false;

}



int main() {
    int peopleNum = 0;
    int method = 0; //0是降序,1是升序

    while (scanf("%d", &peopleNum) != EOF) {
        scanf("%d", &method);
        list StuGrade[peopleNum];
        for (int i = 0; i < peopleNum; i++) {
            scanf("%s %d", &StuGrade[i].name, &StuGrade[i].grade);
            StuGrade[i].seq = i;
        }

        if (method == 1) {//升序
            sort(StuGrade, StuGrade + peopleNum, compare1);
        } else { //降序
            sort(StuGrade, StuGrade + peopleNum, compare2);
        }

        for (int i = 0; i < peopleNum; i++) {
            printf("%s %d\n", StuGrade[i].name, StuGrade[i].grade);
        }
    }
    return 0;
}