有几组测试数据比较坑,就是某些节点可能无法和题目给的首地址的链表连在一起,是独立、游离的,这也算无效节点,如果所有节点都是有效的话,题目就没必要给出一个head变量!
注意,当没有满足题意的节点时,要输出"0 -1"!
代码如下:
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int Key;
int Address;
int Next;
bool flag;
}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(){
for(int i=0;i<maxn;i++){
node[i].flag = false;
}
int N, head;
scanf("%d %d", &N, &head);
int Address, Key, Next;
for(int i=0;i<N;i++){
scanf("%d %d %d", &Address, &Key, &Next);
node[Address].Address = Address;
node[Address].Key = Key;
node[Address].Next = Next;
}
int count = 0;
while(head!=-1){ //count的作用是为了让一些无效节点被排除掉,从题目给的首地址,可能遇到某些数,他与前面给的数不能连成一个链表!!!
node[head].flag = true;
count++;
head = node[head].Next;
}
if(count==0) { //特判
printf("0 -1");
return 0;
}
sort(node,node+maxn,cmp);
for(int i=0;i<count-1;i++){
node[i].Next = node[i+1].Address;
}
node[count-1].Next = -1;
printf("%d %05d\n", count, node[0].Address);
for(int i=0;i<count;i++){
if(node[i].Next!=-1) printf("%05d %d %05d", node[i].Address, node[i].Key, node[i].Next); //正确输出-1
else printf("%05d %d -1", node[i].Address, node[i].Key);
if(i<count-1) printf("\n");
}
}
AC截图: