#include <iostream>
#include<algorithm>
using namespace std;
struct cj {
string name;
int y, sore;
} a[10000];
bool cmp1(cj c1, cj c2) { //由小到大
if (c1.sore == c2.sore)return c1.y < c2.y;
else return c1.sore < c2.sore;
}
bool cmp2(cj c1, cj c2) { //由大到小
if (c1.sore == c2.sore)return c1.y < c2.y;
else return c1.sore > c2.sore;
}
int main() {
int n;
int x;
while(scanf("%d",&n) != EOF){
cin>>x;
for(int i=0;i<n;i++)
{
cin>>a[i].name>>a[i].sore;
a[i].y = i;
}
if(x==0)sort(a,a+n,cmp2);
else if(x==1)sort(a,a+n,cmp1);
for(int i=0;i<n;i++)
{
cout<<a[i].name<<" "<<a[i].sore<<endl;
}
}
}
// 64 位输出请用 printf("%lld")