//  #include<bits/stdc++.h>
#include <cstdio>
#include <ios>
#include<iostream>
#include<vector>
#include<algorithm>

using namespace  std;
struct stu_info
{
   char name[90];
   int score;
   int original_index;
};
bool  decrease(stu_info a, stu_info b)
{

    if(a.score !=b.score)
    {
        return a.score >b.score;
    }
    else {
        return a.original_index<b.original_index;
    }

}
bool  increase(stu_info a, stu_info b)
{

    if(a.score !=b.score)
    {
        return a.score < b.score;
    }
    else {
        return a.original_index<b.original_index;
    }
}


 int main()
 {
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        vector<stu_info>stu_list(n);
        int order;
        scanf("%d",&order);
        for(int i=0;i<n;i++)
        {
            scanf("%s %d",stu_list[i].name,&stu_list[i].score);
            stu_list[i].original_index=i;
        }
        if(order==0)
        {
            sort(stu_list.begin(),stu_list.end(), decrease);
        }
        if(order==1)
        {
            sort(stu_list.begin(),stu_list.end(), increase);
        }
        for(auto iter =stu_list.begin();iter!=stu_list.end();iter++)
        {
            printf("%s %d\n",(*iter).name,(*iter).score);
        }
    }

 }