#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node {
int address, data, next;
};
const int NUM = 100001;
node nodes[NUM];
vector<node> list;
int main(){
int fnAdress, n, k;
cin >> fnAdress >> n >> k;
for (int i = 0; i < n; i++) {
node nodet;
cin >> nodet.address >> nodet.data >> nodet.next;
nodes[nodet.address] = nodet;
}
int address = fnAdress;
while (address != -1) {
list.push_back(nodes[address]);
address = nodes[address].next;
}
int size = (int)list.size();
int round = size / k;
for (int i = 0; i < round; i++) {
int start = i * k;
int end = (i + 1) * k;
reverse(list.begin() + start, list.begin() + end);
}
for(int i = 0; i < size - 1; i++){
printf("%05d %d %05d\n", list[i].address, list[i].data, list[i+1].address);
}
printf("%05d %d %d\n", list[size - 1].address, list[size - 1].data, -1);
return 0;
}