#include<algorithm>
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef struct student{
int id;
char name[100];
int score;
}student;
bool com1(student left,student right)
{
if(left.score > right.score){
return true;
}
else if(left.score==right.score&&left.id<right.id)
{
return true;
}
else
return false;
}
bool com2(student left,student right)
{
if(left.score < right.score){
return true;
}
else if(left.score==right.score&&left.id<right.id)
{
return true;
}
else
return false;
}
int main(){
int n;
int dec;
scanf("%d",&n);
scanf("%d",&dec);
student s[1000];
while(scanf("%d",&n)!=EOF&&scanf("%d",&dec)!=EOF){
for(int i=0;i<n;i++)
{
scanf("%s %d",s[i].name,&s[i].score);
s[i].id=i;
}
if(dec==0)
{
sort(s,s+n,com1);
}
else
sort(s,s+n,com2);
for(int i=0;i<n;i++)
{
// printf("%s %d",s[i].name,s[i].score);
cout<<s[i].name<<' '<<s[i].score<<endl;
}
}
}