Note
-
链表
-
题目输入中可能包括无效节点,因此不能在输入数据的while循环中直接令value=1!!!
需要从头节点遍历链表以进行赋值!!! -
注意分析题目中的特殊值。例如本题最后一个测试点,倘若输入全是无效节点,则需要特判,即输出“0 -1”。
Code
#include<bits/stdc++.h>
using namespace std;
struct Node{
int address,key,next,value;
Node(){
value=0;
}
}node[100005];
bool cmp(struct Node a,struct Node b){
if(a.value!=b.value) return a.value>b.value;
else return a.key<b.key;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
int address,n;
cin>>n>>address;
int data,add1,add2,cnt=0;
for(int j=0;j<n;j++){
scanf("%05d %d %05d",&add1,&data,&add2);
node[add1].address=add1;
node[add1].key=data;
node[add1].next=add2;
}
while(address!=-1){ //!
node[address].value=1;
address=node[address].next;
cnt++;
}
sort(node,node+100005,cmp);
int i=0;
if(cnt>0) printf("%d %05d\n",cnt,node[0].address);
else if(cnt==0) printf("0 -1\n"); //头节点是-1时
while(cnt>0&&node[i].value==1){
printf("%05d %d ",node[i].address,node[i].key);
if(node[i+1].value==1)
printf("%05d\n",node[i+1].address);
else
printf("-1\n");
i++;
}
return 0;
}