题目链接:点击打开链接
知识点笔记:
AC代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int key,address,next;
bool flag=false;//结点是否在链表上
}node[maxn];
bool cmp(Node a,Node b){
if(a.flag==false || b.flag==false) return a.flag>b.flag;
else return a.key<b.key;
}
int main(){
int first,n,count=0;
cin>>n>>first;
int address;
for(int i=0;i<n;i++){
scanf("%d",&address);
scanf("%d %d",&node[address].key,&node[address].next);
node[address].address=address;
}
while(first!=-1){
node[first].flag = true;
count++;
first=node[first].next;
}
if(count==0){
printf("0 -1");
}else{
sort(node,node+maxn,cmp);
printf("%d %05d\n",count,node[0].address);
for(int i=0;i<count-1;i++){
printf("%05d %d %05d\n",node[i].address,node[i].key,node[i+1].address);
}
printf("%05d %d -1",node[count-1].address,node[count-1].key);
}
return 0;
}