PAT A1097 题解+case2的坑

6 篇文章 0 订阅

题目连接

这个题是个stl模拟链表的题目,按理来说应该是个水题,但写完直接case2段错误,就很尴尬。
先看一下题意思:大致意思是,给定一个链表,你需要给链表去重,重复标准是:abs(key)已经出现过,把后出现的重复节点删掉,但是输出时要先输出去重后的链,之后输出删除的节点连成的链。
输入:首个节点的地址 节点数n 下面n行是节点的信息
输出:两条链
题意很清楚,就是根据key值做重复的删减。可以用个结构体存节点信息,先把随机输入的节点连成一条链,然后再做删减。在判定重复时,可以将abs(key)插入到set中,枚举过程中,每次检验set中是否已经存在该值,存在就删除,也就是保存到一个vector中,不存在就插入进去,并且将该节点保存到需要第一个输出的数组中。
思路也很简单,但是case2直接段错误了。。。
很尴尬,我开始以为是数组开小了,开到1e8+10,一样段错误,参考别的大佬的代码找到了原因:是stl引起的,参考博客有可能存在某个串为空的情况,需要输出时加一个判断就好了。
源码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>

using namespace std;

const int maxn = 1e6+10, inf = 0x3f3f3f3f;

struct Node {
	int address, key, next;
};
Node v[maxn];
vector <Node> node, res;
set <int> s;
int n, _first;

int main() {
	cin >> _first >> n;
	for (int i = 0; i < n; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		Node nn;
		nn.address = a, nn.key = b, nn.next = c;
		v[a] = nn;
	}
	for (; _first != -1; _first = v[_first].next) {
		if (s.find(abs(v[_first].key)) == s.end()) {
			s.insert(abs(v[_first].key));
			res.push_back(v[_first]);
		} else {
			node.push_back(v[_first]);
		}

	}
	if (res.size() > 0) {
		for (int i = 0; i < res.size()-1; i++)
        	printf("%05d %d %05d\n", res[i].address, res[i].key, res[i+1].address);
    	printf("%05d %d -1\n", res[res.size()-1].address, res[res.size()-1].key);
	}	
	if (node.size() > 0) {
		for (int i = 0; i < node.size()-1; i++)
	        printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
	    printf("%05d %d -1\n", node[node.size()-1].address, node[node.size()-1].key);
	}
	return 0;
}

编码不规范,debug泪两行…⊛_⊛
欢迎大佬们指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

max_tanAlpha

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值