Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
题解
使用静态链表,需要注意两种特殊情况:
情况一:
Input:
3 99999 //开始地址不在以下地址中
11111 100 -1
00001 0 22222
22222 1000 12345
Output:
0 -1
情况二:
Input:
3 00001
11111 100 -1
00001 0 11111
22222 1000 12345 //地址无法连接,无效地址
Output:
2 00001
00001 0 11111
11111 100 -1
代码:
#include <iostream>
#include <climits>
#include <algorithm>
const int MAXN = 100010;
using namespace std;
struct Node{
int address;
int data;
int next;
bool flag;
}node[MAXN];
bool cmp(Node a,Node b){
if(!a.flag || !b.flag){
return a.flag > b.flag;//无效地址直接往后移动
}
return a.data < b.data;
}
int _1052(){
for(int i =0;i < MAXN;i++){
node[i].flag = false;
}
int n,f_ad;
cin >> n >> f_ad;
int address, data,next;
for(int i=0 ;i<n;i++){
cin >> address >> data >> next;
node[address].address = address;
node[address].data = data;
node[address].next = next;
}
int count =0,p=f_ad;
while(p!=-1){
node[p].flag = true;
count++;
p = node[p].next;
}
if(count==0){
printf("0 -1");
}
else{
sort(node,node+MAXN,cmp);
printf("%d %05d\n",count,node[0].address);
int i;
for(i=0;i<count;i++){
if(!node[i+1].flag){
printf("%05d %d %d\n",node[i].address,node[i].data,-1);
}else{
printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
}
}
}
return 0;
}