let str;
while(str = readline()){
  let res = [],old=[];
  const sortType = readline();
  for(let i=0;i<parseInt(str);i++){
    let arr = readline().split(' ');
    res.push({'name':arr[0],'count':arr[1],'index':i})
    old.push(arr[1])
  }
  //先按成绩排序
  old.sort((a,b)=>{return sortType==0?(b-a):(a-b)})

  //注意这里数字要去重
  for(let v of new Set(old)){
    for(let j in res){
      //这里其实就是按照输入顺序排序
      if(res[j].count ==v){
        console.log(res[j].name,res[j].count)
      }
    }
  }
}