题解
类似于数组模拟链表,开一个1e5大小的数组,存储当前元素节点和下一个节点标号。
从链表头开始将链表压缩在一起并保留相对位置关系存入vec,再根据题目要求首尾交替的存入ans数组。
最后根据ans的相对位置关系,根据题目要求模拟链表的格式输出。注意遍历ans时不能用n来代表范围,因为有多余节点。
AC代码
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e5 + 10;
struct node
{
int val, nxt;
}ls[N];
int main()
{
#ifdef LOCAL
//freopen("C:/input.txt", "r", stdin);
#endif
int h, n;
cin >> h >> n;
for (int i = 0; i < n; ++i)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
ls[a] = { b, c };
}
vector<node> vec, ans;
for (int i = h; ~i; i = ls[i].nxt)
vec.push_back({ ls[i].val, i });
int l = 0, r = vec.size() - 1; //3号样例有多余节点不能为n!!!
while (l <= r)
{
ans.push_back(vec[r--]);
if (l <= r)
ans.push_back(vec[l++]);
}
for (int i = 0; i < vec.size(); ++i)
{
printf("%05d %d ", ans[i].nxt, ans[i].val);
if (i != vec.size() - 1)
printf("%05d\n", ans[i + 1].nxt);
else
printf("-1\n");
}
return 0;
}