题目
思路
先用线性数组将链表信息存储到数组中,每个数组中的信息包括下一个索引和值,然后在用vector模拟链表存储当前结点和值,按值排序后输出
坑点
测试点4会出现段错误的情况:忽略了输入结点全是无效结点的情况,应输出0 -1。
代码
#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define nmax 100005
#define inf 999999
int N[nmax];
int Key[nmax];
int n;
int first_ad;
struct Node
{
int ad;
int key;
};
vector<Node> vec;
bool cmp(const Node& a, const Node& b)
{
return a.key < b.key;
}
int main()
{
cin >> n >> first_ad;
for (int i = 0; i < n; ++i) {
int cur_ad, key, next_ad;
cin >> cur_ad >> key >> next_ad;
N[cur_ad] = next_ad;
Key[cur_ad] = key;
}
int cur_ad = first_ad;
while (cur_ad != -1) {
Node node;
node.ad = cur_ad;
node.key = Key[cur_ad];
vec.emplace_back(node);
cur_ad = N[cur_ad];
}
sort(vec.begin(), vec.end(), cmp);
if (vec.empty()) {
printf("0 -1");
return 0;
}
printf("%d %05d\n", n, vec[0].ad);
for (int i = 0; i < vec.size()-1; ++i) {
printf("%05d %d %05d\n", vec[i].ad, vec[i].key, vec[i + 1].ad);
}
printf("%05d %d -1", vec[vec.size() - 1].ad, vec[vec.size() - 1].key);
return 0;
}