//土尔逊Torson 编写于2023/4/11
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <algorithm>
#include <stdlib.h>

using namespace std;

struct student {
	char name[50];
	int grade;
	int seq;
};

bool comp0(student left, student right) {
	if (left.grade > right.grade) {
		return true;
	}
	else if (left.grade == right.grade && left.seq < right.seq) {
		return true;
	}
	else {
		return false;
	}
}

bool comp1(student left, student right) {
	if (left.grade < right.grade) {
		return true;
	}
	else if (left.grade == right.grade && left.seq < right.seq) {
		return true;
	}
	else {
		return false;
	}
}

int main() {
	int n;
	int order;
	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, comp0);
		}
		else {
			sort(arr, arr + n, comp1);
		}

		for (int j = 0; j < n; ++j) {
			printf("%s %d\n", arr[j].name, arr[j].grade);
		}
	}
	system("pause");
	return EXIT_SUCCESS;
}
// 64 位输出请用 printf("%lld")