#include <stdio.h>
#include <stdlib.h>
#define ElementType int
#define Maxsize 100000
typedef struct node Node;
typedef struct list* List;
struct node{
ElementType Data;
int Next;
};
struct list{
Node Line[Maxsize];
int head;
int K;
int N;
};
List Read();
void Reverse(List L);
void Print(List L);
int main(int argc, char *argv[]) {
List L=Read();
Reverse(L);
Print(L);
return 0;
}
List Read(){
List L=(List)malloc(sizeof(struct list));
int i,j,cnt=0;
scanf("%d%d%d",&L->head,&L->N,&L->K);
for(i=0;i<L->N;i++){
scanf("%d",&j);
scanf("%d%d",&L->Line[j].Data,&L->Line[j].Next);
}
i=L->head;
while(i!=-1){
cnt++;
i=L->Line[i].Next;
}
L->N=cnt;
return L;
}
void Reverse(List L){
if(L->N==1 || L->K>L->N || L->K==1) return;
Node* line=L->Line;
int k=L->K;
int i,j,n=L->N/L->K;
int Old=L->head,New=line[L->head].Next,tNext;
int flag=0;
int thead,tlast=L->head,tlastL=tlast;
for(i=1;i<=n;i++){
for(j=1;j<k;j++){
tNext=line[New].Next;
line[New].Next=Old;
Old=New;
New=tNext;
}
thead=Old;
if(!flag) {
L->head=thead;
flag=1;
}
else{
line[tlastL].Next=thead;
tlastL=tlast;
}
if(i==n) break;
tlast=New;
Old=tNext;
New=line[tNext].Next;
}
line[tlast].Next=tNext;
}
void Print(List L){
Node* line=L->Line;
int i=L->head;
while(i!=-1){
printf("%05d %d ",i,line[i].Data);
if(line[i].Next==-1) printf("-1\n");
else printf("%05d\n",line[i].Next);
i=line[i].Next;
}
}