这道题我用了两种输出方法,搞不明白为什么第一种输出方法会有一个点段错误,扣了两分,难道这两个输出方法不等价吗。有好心人看到帮我解答一下
PS:感谢考研群里面一个学弟的提示,方法一的输出默认了left和right向量长度不为零,但是一旦出现向量长度为零的情况,输出-1的那一行就会造成段错误。
方法一:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
struct node
{
int key;
int next;
} add[100005];
int have[10005] = {0};
int main()
{
int n, start, address, p;
scanf("%d %d", &start, &n);
for(int i = 0; i < n; i++) {
scanf("%d", &address);
scanf("%d %d", &add[address].key, &add[address].next);
}
vector<node> left, right; //right记录移除的链表
p = start;
while(p != -1) {
int index = abs(add[p].key);
if(have[index] == 0) {
have[index] = 1;
left.push_back(node{add[p].key, p}); //结构体重载,只需要记录结点的地址和key值
} else if(have[index] == 1) {
right.push_back(node{add[p].key, p});
}
p = add[p].next;
}
for(int i = 0; i < left.size() - 1; i++)
printf("%05d %d %05d\n", left[i].next, left[i].key, left[i+1].next);
printf("%05d %d -1\n", left[left.size()-1].next, left[left.size()-1].key);
for(int i = 0; i < right.size() - 1; i++)
printf("%05d %d %05d\n", right[i].next, right[i].key, right[i+1].next);
printf("%05d %d -1\n", right[right.size()-1].next, right[right.size()-1].key);
return 0;
}
方法二:(仅输出方式不同)
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
struct node
{
int key;
int next;
} add[100010];
int have[10010] = {0};
int main()
{
int n, start, address, p;
scanf("%d %d", &start, &n);
for(int i = 0; i < n; i++) {
scanf("%d", &address);
scanf("%d %d", &add[address].key, &add[address].next);
}
vector<node> left, right;
p = start;
while(p != -1) {
int index = abs(add[p].key);
if(have[index] == 0) {
have[index] = 1;
left.push_back(node{add[p].key, p});
} else if(have[index] == 1) {
right.push_back(node{add[p].key, p});
}
p = add[p].next;
}
for(int i = 0; i < left.size(); i++) {
printf("%05d %d ", left[i].next, left[i].key);
if(i+1 != left.size()) printf("%05d\n", left[i+1].next);
else printf("-1\n");
}
for(int i = 0; i < right.size(); i++) {
printf("%05d %d ", right[i].next, right[i].key);
if(i+1 != right.size()) printf("%05d\n", right[i+1].next);
else printf("-1\n");
}
return 0;
}