#include<cstdio>
#include<algorithm>

using namespace std ;

struct Student {
    char name[50];
    int grade;
    int seq;//记录录入顺序
};
bool comp0(Student lhs, Student rhs) {
    if (lhs.grade < rhs.grade) {
        return true;
    } else if (lhs.grade == rhs .grade && lhs.seq < rhs.seq) {
        return true;
    } else {
        return false;
    }
}
bool comp1(Student lhs, Student rhs) {
    if (lhs.grade > rhs.grade) {
        return true;
    } else if (lhs.grade == rhs .grade && lhs.seq < rhs.seq) {
        return true;
    } else {
        return false;
    }
}

int main() {
    int n ;
    int order; //0/1
    Student arr[1000];
    while (scanf("%d%d", &n, &order) != EOF) {
        int seq = 0;
        for (int i = 0 ; i < n ; ++i) {
            scanf("%s%d", arr[i].name, &arr[i].grade);
            arr[i].seq = seq;
            ++seq;
        }
        if (0 == order) {
            sort(arr, arr + n, comp1);
        } else if (1 == order) {
            sort(arr, arr + n, comp0);
        }
        for (int i = 0 ; i < n ; ++i) {
            printf("%s %d\n", arr[i].name, arr[i].grade);
        }
    }

}