#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef struct
{
	int sequence;
	string name;
	int grade;
}student;
bool compare1(student a, student b)
{
	if (a.grade < b.grade)
	{
		return true;
	}
	else if (a.grade > b.grade)
	{
		return false;
	}
	if (a.sequence < b.sequence)
	{
		return true;
	}
	else return false;
}
bool compare2(student a, student b)
{
	if (a.grade > b.grade)
	{
		return true;
	}
	else if (a.grade < b.grade)
	{
		return false;
	}
	if (a.sequence < b.sequence)
	{
		return true;
	}
	else return false;
}

int main()
{
	
	int n, tag;
	while (scanf("%d",&n)!=EOF)
	{student array[n];
		scanf("%d", &tag);
		for (int i = 0; i < n; i++)
		{
			array[i].sequence = i;
		cin>>array[i].name>>array[i].grade;
		}
		if (tag == 1)
		{
			sort(array, array + n,compare1);
		}
		else
		{
			sort(array, array + n, compare2);
		}
		for (int i = 0; i < n; i++)
		{
			cout<<array[i].name<<" "<<array[i].grade<<endl;
		}

	}
	return 0;
}