#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct student {
string name;
int score;
};
int j;
bool cmd1(student a, student b) {
if(j==0){
return a.score>b.score;
}
else
{
return a.score<b.score;
}
}
void testCase(int n, int j) {
vector<student> st;
for (int i = 0; i < n; i++) {
student st1;
cin >> st1.name >> st1.score;
st.push_back(st1);
}
stable_sort(st.begin(), st.end(), cmd1);
for (auto& i : st) {
cout << i.name << ' ' << i.score << endl;
}
}
int main() {
int n;
while(cin >> n)
{
cin >> j;
testCase(n,j);
}
return 0;
}