include

include

include

include<string.h>

using namespace std;
typedef struct Student {
char name[50];
int score;
int n;
}stu;
bool compare1(stu A, stu B) {
if(A.score==B.score)
return A.n<B.n;
else
return A.score > B.score;
}
bool compare2(stu A, stu B) {
if(A.score==B.score)
return A.n<B.n;
else
return A.score < B.score;
}
stu s[100];
int main() {
int method, n;
while(scanf("%d\n%d", &n, &method)!=EOF){

for (int i = 0; i < n; i++) {
    scanf("%s %d ", s[i].name, &s[i].score);
    s[i].n=i;
}
if (method == 0)
    sort(s, s + n, compare1);
else
    sort(s, s + n, compare2);
for (int i = 0; i < n; i++) {
    printf("%s %d\n", s[i].name, s[i].score);
}
}
return 0;

}