PAT A1052(测试点1答案错误)

自认为考虑很全面,殊不知,对无效结点的考虑存在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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值