#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
//stable_sort函数第一次用,如果不知道可以用sort函数,只不过结构体中得加一个位序变量,
//记录输入时的顺序,编写cmp规则时,当分数相同可按位序小的优先进行排序
struct Student{
string name;
int score;
}stu;
vector<Student> v;
bool cmp0(Student a, Student b);
bool cmp1(Student a, Student b);
int main(){
int n, sort_way;
while(cin >> n >> sort_way){
for(int i = 0; i < n; i++){
cin >> stu.name >> stu.score;
v.push_back(stu);
}
if(sort_way) stable_sort(v.begin(),v.end(),cmp1);//从低到高
else stable_sort(v.begin(),v.end(),cmp0);//从高到低
for(int i = 0; i < n; i++){
cout << v[i].name << ' ' << v[i].score << endl;
}
}
}
bool cmp0(Student a, Student b){
return a.score > b.score;
}
bool cmp1(Student a, Student b){
return a.score < b.score;
}