link
![](https://img2020.cnblogs.com/blog/1929461/202004/1929461-20200415210651951-1835055016.png)
#include <iostream>
#define LL long long
using namespace std;
int N,K;
int nextadd[100000];
int val[100000];
int helper(int head){
int cur=head;
int cnt=1;
if(cnt==K) return head;
while(true){
cur=nextadd[cur];
cnt++;
if(cur==-1) return head;
if(cnt==K) break;
}
int nextpartstart=-1;
if(nextadd[cur]!=-1) nextpartstart=helper(nextadd[cur]);
nextadd[cur]=-1;
int pre=-1;
int curpartend=head;
cur=head;
while(cur!=-1){
int tmpnext=nextadd[cur];
nextadd[cur]=pre;
pre=cur;
cur=tmpnext;
}
nextadd[curpartend]=nextpartstart;
return pre;
}
int main(){
int head;
cin>>head;
cin>>N>>K;
for(int i=1;i<=N;i++){
int add,value,next;
cin>>add>>value>>next;
val[add]=value;
nextadd[add]=next;
}
int newhead=helper(head);
int cur=newhead;
while(cur!=-1){
if(nextadd[cur]!=-1) printf("%05d %d %05d
", cur,val[cur],nextadd[cur]);
else printf("%05d %d -1
", cur,val[cur]);
cur=nextadd[cur];
}
return 0;
}