#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct stu{
string name;
int score;
}student[200];
bool cmp1(stu a,stu b){
return a.score < b.score;
}
bool cmp2(stu a,stu b){
return a.score > b.score;
}
int main()
{
int num,flag;
while(cin >> num >> flag){
for(int i = 0;i < num;i ++){
cin >> student[i].name >> student[i].score;
}
if(flag) stable_sort(student,student + num,cmp1);
else stable_sort(student ,student + num,cmp2);
for(int j = 0;j < num;j ++){
cout << student[j].name << " " << student[j].score << endl;
}
}
return 0;
}