这一道题卡了很久。。。说实话是没考虑到测试用例的多样性,好在牛客网上面公布了一些测试用例,让我知道哪块出现了问题;
上述的测试用例显示了问题所在,其问题就是虽然输入了节点,但是起始节点压根跟该节点没关系;
这道题彰显的有两个要点:
其一:cmp函数的自定义使用,利用cmp来达到自己的排序目的;
其二:关于静态链表中有序节点的存贮。其实下述代码解法中比较重要的点就是利用标志位强行将有效节点排序在左侧,这样可以实现索引的坐标访问,更加有效,但是使用这个方法之前,一定要将节点中建立地址和后继信息,以便和数组下标进行分离。
#include<stdlib.h>
#include<stdio.h>
#include<algorithm>
const int maxn=100001;
struct node{
int adress;
int key;
int next;
bool flag;
}nodelist[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(){
for(int i=0;i<maxn;i++){
nodelist[i].flag=false;
}
int num,head,address;
scanf("%d%d",&num,&head);
int count=0,p=head;
for(int i=0;i<num;i++){
scanf("%d",&address);
scanf("%d%d",&nodelist[address].key,&nodelist[address].next);
nodelist[address].adress=address;
}
while(p!=-1){
nodelist[p].flag=true;
p=nodelist[p].next;
count++;
}
if(count==0){
printf("0 -1");
}else{
std::sort(nodelist,nodelist+maxn,cmp);
printf("%d %05d\n",count,nodelist[0].adress);
for(int i=0;i<count;i++){
if(i!=count-1){
printf("%05d %d %05d\n",nodelist[i].adress,nodelist[i].key,nodelist[i+1].adress);
}else{
printf("%05d %d -1\n",nodelist[i].adress,nodelist[i].key);
}
}
}
system("pause");
}