#include<bits/stdc++.h>
using namespace std;
#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long
#define ull unsigned long long
#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<int,int>
#define piii pair<int,pii>
#define fi first
#define se second
#define mk(x,y) make_pair(x,y)
#define base 2333
const int mod=1e9+7;
const int maxn=1e5+10;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){
if(y==0) return x;
return gcd(y,x%y);
}
int init,fst,n,k,x,tmp=0,neghead=0;
int nxt[maxn],dat[maxn],khead;
string f(int x){
if(x==-1) return "-1";
string s="";
while(x) s+=('0'+(x%10)),x/=10;
while(s.size()<5) s+='0';
reverse(s.begin(),s.end());
return s;
}
vector<int> v1,v2,v3;
int main(){
ios::sync_with_stdio(false);
cin>>fst>>n>>k;
while(n--){
cin>>x;
cin>>dat[x]>>nxt[x];
}
while(fst!=-1){
if(dat[fst]<0) v1.push_back(fst);
else if(dat[fst]<=k) v2.push_back(fst);
else v3.push_back(fst);
fst=nxt[fst];
}
rep(i,0,v2.size()) v1.push_back(v2[i]);
rep(i,0,v3.size()) v1.push_back(v3[i]);
rep(i,0,v1.size()){
cout<<f(v1[i])<<" "<<dat[v1[i]]<<" ";
if(i+1<v1.size()) cout<<f(v1[i+1]);
else cout<<"-1";
cout<<"\n";
}
return 0;
}