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