#include<deque> #include<cstdio> #include<algorithm> using namespace std; const int N=100005; struct node { int data,next,addr; node(){} node(int a,int b,int c):addr(a),data(b),next(c){} }; node so[N]; deque<node>sr; int main() { int start,n,k; scanf("%d%d%d",&start,&n,&k); for(int a,b,c,i=0;i<n;++i) { scanf("%d%d%d",&a,&b,&c); so[a].addr=a, so[a].data=b, so[a].next=c; } do sr.push_back(so[start]); while((start=so[start].next)!=-1); for(int i=0;i+k<=sr.size();i+=k) reverse(sr.begin()+i,sr.begin()+i+k); for(int i=0;i<sr.size()-1;++i) sr[i].next=sr[i+1].addr; sr[sr.size()-1].next=-1; int i; for( i=0;i<sr.size()-1;++i) printf("%05d %d %05d\n",sr[i].addr,sr[i].data,sr[i].next); printf("%05d %d %d\n",sr[i].addr,sr[i].data,sr[i].next); return 0; }