#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
#include<queue>
#include<unordered_set>
using namespace std;
const int maxn = 100001;
vector<int>fushu, xiaoyu, dayu, v;
struct node
{
int address,data, next;
}Node[maxn];
int main()
{
int st, n, k; int address, data,next;
cin >> st >> n >> k;
for (int i = 0; i < n; i++)
{
cin >> address;
Node[address].address = address;
cin >> Node[address].data >> Node[address].next;
}
int j = st;
while (j != -1)
{
if (Node[j].data > k)
{
dayu.push_back(j);
}
else if (Node[j].data <= k && Node[j].data >= 0)
{
xiaoyu.push_back(j);
}
else
{
fushu.push_back(j);
}
j = Node[j].next;
}
int q = 0;
v.resize(maxn);
for (int i = 0; i < fushu.size(); i++)
{
v[q++] = fushu[i];
}
for (int i = 0; i < xiaoyu.size(); i++)
{
v[q++] = xiaoyu[i];
}
for (int i = 0; i < dayu.size(); i++)
{
v[q++] = dayu[i];
}
for (int i = 0; i < q; i++)
{
if(i!=q-1)
printf("%05d %d %05d
", v[i], Node[v[i]].data, Node[v[i+1]].address);
else
printf("%05d %d -1", Node[v[i]].address, Node[v[i]].data);
}
}