原题链接:PTA | 程序设计类实验辅助教学平台
Tips:以下Python代码仅个人理解,非最优算法,仅供参考!多学习其他大佬的AC代码!
import sys
# 读取输入
head, n, k = map(int, sys.stdin.readline().split())
# 初始化数据,装入字典,最终取值
data = {}
next = {}
for _ in range(n):
_address, _data, _next = map(int, sys.stdin.readline().split())
data[_address] = _data
next[_address] = _next
# 创建节点列表,构建链表
nodes = []
p = head
while p != -1:
nodes.append(p)
p = next[p]
# 测试点6:给的数据有多余结点,更新 n 为实际有效数量
n = len(nodes)
# 分割成组,并直接逆转
res = [nodes[i:i + k] for i in range(0, n, k)][::-1]
# 合并为一个扁平化列表
results = [address for group in res for address in group if group]
# 输出结果
for index in range(len(results) - 1):
sys.stdout.write(f'{results[index]:05d} {data[results[index]]} {results[index + 1]:05d}\n')
sys.stdout.write(f'{results[-1]:05d} {data[results[-1]]} -1\n')
标签:index,PAT,Python,results,next,sys,1110,address,data
From: https://blog.csdn.net/m0_56677113/article/details/142945331