#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
bool cmp1(const pair<string, int> p1, const pair<string, int> p2) {
     return p1.second > p2.second;
}
bool cmp2(const pair<string, int> p1, const pair<string, int> p2) {
     return p1.second < p2.second;
}
int  main()
{
    std::ios::sync_with_stdio(false);
    int n,sel,score;
    string name;
    while(cin >> n){
        cin >> sel;
        vector<pair<string, int> > vec;
        while (n--) {
            cin >> name >> score;
            vec.push_back(pair<string, int>(name,score));
        }
        if(sel == 0)
            stable_sort(vec.begin(), vec.end(), cmp1);
        else
            stable_sort(vec.begin(), vec.end(), cmp2);
        for (auto it = vec.begin(); it != vec.end(); ++it)
            cout << (*it).first << " " << (*it).second << endl;
    }
    return 0;
}