
#include <bits/stdc++.h>
#include<math.h>
#include <string>
using namespace std;
const int maxn = 100005;
const int TABLE = 1000010;
struct Node{//定义静态链表
int data;
int address;
int next;
int order;
}node[maxn];
bool isExist[TABLE] = {false};
bool cmp(Node a,Node b){
return a.order < b.order;
}
int main(){
memset(isExist,false,sizeof(isExist));
for(int i=0;i<maxn;++i){//初始化
node[i].order = 2 * maxn;//表示初始时均为无效节点
}
int n,begin,address;
scanf("%d%d",&begin,&n);
for(int i=0;i<n;++i){
scanf("%d",&address);
scanf("%d%d",&node[address].data,&node[address].next);
node[address].address = address;
}
//未删除的有效节点个数和已删除的有效节点个数
int countValid = 0, countRemoved = 0,p = begin;
while(p != -1){
if(!isExist[abs(node[p].data)]){
isExist[abs(node[p].data)] = true;
node[p].order = countValid++;
}else{
node[p].order = maxn+ countRemoved++;//被删除,编号从maxn开始
}
p = node[p].next;
}
sort(node,node+maxn,cmp);
//输出结果
int count = countValid + countRemoved;
for(int i= 0;i<count;++i){
if(i != countValid -1 && i != count -1){//非最后一个节点
printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
}else{
printf("%05d %d -1\n",node[i].address,node[i].data);
}
}
system("pause");
return 0;
}