#include <bits/stdc++.h>
using namespace std;

typedef struct student{
	string name;
	int grade;
	int id;
	
}Student;

// 升序排列 
bool my_cmp_up(const Student &a, const Student& b){
	return a.grade < b.grade; 
}

bool my_cmp_down(const Student& a, const Student& b){
	return a.grade > b.grade;
}

int main(){
	int num_stu;
	int sort_way;
	int id;

	
	while(cin >> num_stu >> sort_way){
		vector<Student> stu;
		for (int i=0; i<num_stu; i++){
			string t_name;
			int t_grade;
			int t_id;
			cin >> t_name >> t_grade;
			stu.push_back({t_name,t_grade,t_id});
		}
		
		if (sort_way == 1){
			stable_sort(stu.begin(), stu.end(), my_cmp_up);
		}
		else{
			stable_sort(stu.begin(), stu.end(), my_cmp_down);
		} 

		for (auto item: stu){
			cout << item.name << " " << item.grade << endl;
		}
	}	
	
	
	return 0;
}