#include<iostream>
#include<algorithm>
#define maxn 100005
using namespace std;
int k=0;
struct Node{
int address,data,next,inList,oriorder;
}node[maxn];
bool cmp(Node a, Node b){
if(!a.inList||!b.inList) return a.inList>b.inList;
if((a.data>=0&&b.data<0)||(a.data<0&&b.data>=0))
return a.data<b.data;
if((a.data>k&&b.data<=k)||(a.data<=k&&b.data>k))
return a.data<b.data;
return a.oriorder<b.oriorder;
}
int main(){
int n,head,address,data,next,count=0;
scanf("%d%d%d",&head,&n,&k);
for(int i=0;i<n;i++){
scanf("%d%d%d",&address,&data,&next);
node[address]={
address,data,next,0,0};
}
for(int p=head;p!=-1;p=node[p].next){
node[p].inList=1;
node[p].oriorder=count;
count++;
}
sort(node,node+maxn,cmp);
for(int i=0;i<count-1;i++)
printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
printf("%05d %d -1\n",node[count-1].address,node[count-1].data,-1);
return 0;
}