#include "cstdio"
#include "algorithm"

using namespace std;

struct Student {
    char name[100];
    unsigned int score;
    unsigned int seq;
};

bool comp_asc(struct Student stu1, struct Student stu2) {
    if (stu1.score < stu2.score) {
        return true;
    } else if (stu1.score == stu2.score) {
        return stu1.seq < stu2.seq;
    }
    return false;
}

bool comp_desc(struct Student stu1, struct Student stu2) {
    if (stu1.score > stu2.score) {
        return true;
    } else if (stu1.score == stu2.score) {
        return stu1.seq < stu2.seq;
    }
    return false;
}

int main() {
    int n, asc;
    while (EOF != scanf("%d %d", &n, &asc)) {
        struct Student studs[n];
        for (int i = 0; i < n; ++i) {
            int id, score;
            scanf("%s %d", studs[i].name, &studs[i].score);
            studs[i].seq = i;
        }
        if (1 == asc) {
            sort(studs, studs + n, comp_asc);
        } else {
            sort(studs, studs + n, comp_desc);
        }
        for (int i = 0; i < n; i++) {
            printf("%s %d\n", studs[i].name, studs[i].score);
        }
    }

    return 0;
}