# 树编码为prufer序列
# 所有节点编号从1到max_node_num
class PruferEncoder:
def __init__(self, edges, max_node_num, is_directed = False):
self.is_directed = is_directed
self.max_node_num = max_node_num
self.link = [[] for _ in range(max_node_num+1)]
self.valid = [1] * (max_node_num + 1)
self.__d = [0] * (max_node_num + 1)
for a, b in edges:
if is_directed:
self.link[b].append(a)
self.__d[a] += 1
else:
self.link[a].append(b)
self.link[b].append(a)
self.__d[a] += 1
self.__d[b] += 1
def __remove_node(self, node):
for other in self.link[node]:
self.__d[other] -= 1
self.valid[node] = 0
def encode(self):
ans = []
for i in range(1, self.max_node_num+1):
if len(ans) == self.max_node_num - 2:
break
if (self.is_directed == True and self.__d[i] == 0) or (self.is_directed == False and self.__d[i] == 1):
for node in self.link[i]:
if self.valid[node]:
ans.append(node)
break
self.__remove_node(i)
while ((self.is_directed == True and self.__d[ans[-1]] == 0) or (self.is_directed == False and self.__d[ans[-1]] == 1)) and ans[-1] < i and len(ans) < self.max_node_num - 2:
for node in self.link[ans[-1]]:
if self.valid[node]:
ans.append(node)
break
self.__remove_node(ans[-2])
return ans
# prufer序列解码为边列表,不区分是有向图的编码序列还是无向图的编码序列,都能正确解码
# 所有节点编号从1到max_node_num
from queue import PriorityQueue
class PruferDecoder():
def __init__(self, encode_list, max_node_num):
self.data = encode_list[::]
self.max_node_num = max_node_num
def decode(self):
d = [0] * (self.max_node_num+1)
for node in self.data:
d[node] += 1
d[self.max_node_num] = 1
min_heap = PriorityQueue()
for node in range(1, self.max_node_num+1):
if d[node] == 0:
min_heap.put(node)
ans = []
for node in self.data:
ans.append((node, min_heap.get()))
d[node] -= 1
if d[node] == 0:
min_heap.put(node)
ans.append((self.max_node_num, min_heap.get()))
return ans
n, t = map(int, input().split())
if t == 1:
edges = []
arr = list(map(int, input().split()))
for i, node in enumerate(arr):
edges.append((node, i+1))
ans = PruferEncoder(edges, n, is_directed=True).encode()
for val in ans:
print(val, end=' ')
print()
else:
arr = list(map(int, input().split()))
edges = PruferDecoder(arr, n).decode()
ans = [0] * (n-1)
for a, b in edges:
ans[b-1] = a
for val in ans:
print(val, end=' ')
print()