#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
struct node
{
int data,next;
}listt[N];
int main()
{
int head,n,add;
cin>>head>>n;
int vis[N]={0}; //标记
int old[N]={0},k1=0;
int neww[N]={0},k2=0;
for(int i=1;i<=n;i++)
{
cin>>add;
cin>>listt[add].data>>listt[add].next;
}
int p=head;
while(p!=-1)
{
int m=fabs(listt[p].data);
if(!vis[m])
{
vis[m]=1;
old[k1++]=p; //存放的是前面的地址
}
else
{
neww[k2++]=p; //存放的是前面的地址
}
p=listt[p].next;
}
printf("%05d",head);
for(int i=1;i<k1;i++)
{
printf(" %d %05d
%05d",listt[old[i-1]].data,old[i],old[i]);
}
printf(" %d %d
",listt[old[k1-1]].data,-1);
if(k2>0)
{
printf("%05d",neww[0]);
for(int i=1;i<k2;i++)
{
printf(" %d %05d
%05d",listt[neww[i-1]].data,neww[i],neww[i]);
}
printf(" %d %d
",listt[neww[k2-1]].data,-1);
}
return 0;
}