#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

using student = struct student {
    string name;
    int grade;
    struct student* next=nullptr;
};

void LSort( student* head, int c ) {
    if (head->next == nullptr)
        return;
    student* p = head;
    student* q = head->next;
    while (q->next != nullptr ) {
        if (c == 1) {
            if (p->next->grade > q->next->grade) {
                p = q;
                q = q->next;
            }else {
            q=q->next;
            }

        } else {
            if (p->next->grade < q->next->grade) {
                p = q;
                q = q->next;
            }else {
            q=q->next;
            }
        }
    }
    cout << p->next->name << ' '<< p->next->grade << endl;
    q = p->next;
    p->next = q->next;
    free(q);
    LSort(head, c);
}



int main() {

    int n;
    int c;
    while (cin >> n) {
        cin >> c;
        auto* head = new student, *p=head;
        while (n--) {
           auto* stu = new student;
            cin >> stu->name >> stu->grade;
            p->next = stu;
            stu->next = nullptr;
            p=stu;
        }
        LSort(head, c);
    }
    return 0;

}