自认为考虑很全面,殊不知,对无效结点的考虑存在bug
以下代码中对key赋初值,只能说明这个结点存在,并不能说明这个结点在链表上。然而只有在链表上的结点,才能算是有效结点。
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int address, key, next;
Node() { key = 100010; }
}node[maxn];
bool cmp(Node a, Node b) {
return a.key < b.key;
}
int main() {
int n, head, address;
cin >> n >> head;
for(int i = 0; i < n; i++) {
cin >> address;
cin >> node[address].key >> node[address].next;
node[address].address = address;
}
int cur = head, num = 0;
while(cur != -1) {
cur = node[cur].next;
num++;
}
if(num == 0) printf("0 -1");
else {
sort(node, node + maxn, cmp);
printf("%d %05d\n",num, node[0].address);
for(int i=0; i<num; i++) {
if(i!=num-1) printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
else printf("%05d %d -1\n", node[i].address, node[i].key);
}
}
return 0;
}
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int address, key, next;
bool flag;
Node() {
flag = false;
}
}node[maxn];
bool cmp(Node a, Node b) {
if(a.flag != b.flag) return a.flag > b.flag;
return a.key < b.key;
}
int main() {
int n, head, address;
cin >> n >> head;
for(int i = 0; i < n; i++) {
cin >> address;
cin >> node[address].key >> node[address].next;
node[address].address = address;
}
int cur = head, num = 0;
while(cur != -1) {
node[cur].flag = true;
cur = node[cur].next;
num++;
}
if(num == 0) printf("0 -1");
else {
sort(node, node + maxn, cmp);
printf("%d %05d\n",num, node[0].address);
for(int i=0; i<num; i++) {
if(i!=num-1) printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
else printf("%05d %d -1\n", node[i].address, node[i].key);
}
}
return 0;
}