#include<bits/stdc++.h>
using namespace std;
const int Max=1e5+10;
struct Node {
int data;
int next;
} node[Max];
int main() {
int s1,n,k;
scanf("%d %d %d",&s1,&n,&k);
int address;
for(int i=0; i<n; i++) {
scanf("%d ",&address);
scanf("%d %d",&node[address].data,&node[address].next);
}
int count=0;
vector<int> address1(n+1,-1);
address1[0]=s1;
while(address1[count]!=-1) {
count++;
address1[count]=node[address1[count-1]].next;
}
for(int i=0; i+k<=count;i+=k) {
reverse(address1.begin()+i,address1.begin()+i+k);
}
for(int i=0; i<count-1; i++) {
printf("%05d %d %05d\n",address1[i],node[address1[i]].data,address1[i+1]);
}
printf("%05d %d -1\n",address1[count-1],node[address1[count-1]].data);
return 0;
}