#include <iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef struct Student {
string name;
int score;
int order;//记录先后次序
};
bool Zero(Student a, Student b) {
if (a.score == b.score) {
return a.order <
b.order; //相同成绩都按先录入排列在前的规则处理
} else {
return a.score > b.score;
}
}
bool One(Student a, Student b) {
if (a.score == b.score) {
return a.order < b.order;
} else {
return a.score < b.score;
}
}
int main() {
int n;
int method;
while (scanf("%d", &n) != EOF) {
Student stu[n];
scanf("%d", &method);
for (int i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].score;
stu[i].order = i;
}
if (method == 0) {
sort(stu, stu + n, Zero);
} else if (method == 1) {
sort(stu, stu + n, One);
}
for (int j = 0; j < n; j++) {
cout << stu[j].name << " " << stu[j].score;
printf("\n");
}
}
}