#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int MaxSize = 500;
struct Student {
char name[50];
int grade;
int seq;//记录录入的顺序
};
bool comp0(Student lhs, Student rhs) {
//是否交换位置 true:不交换 false:交换
if (lhs.grade > rhs.grade)
return true;
else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
return true;
else return false;
}
bool comp1(Student lhs, Student rhs) {
if (lhs.grade < rhs.grade)
return true;
else if (lhs.grade == rhs.grade && lhs.seq < rhs.seq)
return true;
else return false;
}
int main() {
Student arr[MaxSize];
int n, flag;
while (scanf("%d%d", &n, &flag)!=EOF) {
int seq = 0;
for (int i = 0; i < n; i++) {
scanf("%s%d", &arr[i].name, &arr[i].grade);
arr[i].seq = seq;
seq++;
}
if (flag == 1)
sort(arr, arr + n, comp1);
else
sort(arr, arr + n, comp0);
for (int i = 0; i < n; i++) {
cout << arr[i].name << " " << arr[i].grade << endl;
}
}
}
// 64 位输出请用 printf("%lld")