#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
struct Student{
char name[50];
int grade;
int seq;
};
//从高到底
bool Comp1(Student a, Student b){
if (a.grade == b.grade && a.seq < b.seq) {
return true;
}else {
return a.grade > b.grade;
}
};
//从底到高
bool Comp2(Student a, Student b){
if (a.grade == b.grade && a.seq < b.seq) {
return true;
}else {
return a.grade < b.grade;
}
};
int main() {
int n;
while (scanf("%d",&n) != EOF) {
int flag;
Student stu[n];
scanf("%d",&flag);
for (int i = 0; i < n ; ++i) {
scanf("%s %d",&stu[i].name,&stu[i].grade);
stu[i].seq = i;
}
if (0 == flag) {
sort(stu, stu+n, Comp1);
}else {
sort(stu, stu+n, Comp2);
}
for (int j = 0; j < n; ++j) {
printf("%s %d\n",stu[j].name,stu[j].grade);
}
}
}