#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

struct student{
    string name;
    int score;
    bool operator<(const student& p){
		return (this->name < p.name) && (this->score < p.score);
	}
};

bool Compare1 (student x, student y){ //低到高
    return x.score > y.score;
}

bool Compare2 (student x, student y){ //高到低
    return x.score < y.score;
}
int main() {
    int n, m;
    while (scanf ("%d", &n) != EOF){
		scanf ("%d", &m);
    	student stu[n];
        for (int i = 0; i < n; i++){
            cin >> stu[i].name >> stu[i].score;
        }
        if (m == 1){
            stable_sort (stu, stu + n, Compare2);
        }else {
            stable_sort (stu, stu + n, Compare1);
        }
        for (int i = 0; i < n; i++){
			cout << stu[i].name << ' ' << stu[i].score << endl;
		}
    }
    return 0;
}