菜鸡1号


私信TA

用户名:uq_69651989863

访问量:903

签 名:

等  级
排  名 1215
经  验 2998
参赛次数 0
文章发表 48
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

解题思路:

注意事项:

参考代码:

def find_root(tree):
   # 找到根节点
   nodes = set(tree.keys())
   children = set()
   for node in tree.values():
       children.update(node)
   return (nodes - children).pop()


def find_max_children(tree):
   # 找到孩子最多的节点
   max_node = None
   max_count = 0
   for node, children in tree.items():
       if len(children) > max_count:
           max_node = node
           max_count = len(children)
   return max_node


def find_children(tree, node):
   # 找到节点的孩子
   return sorted(tree[node])


# 读取输入
n, m = map(int, input().split())  # 结点个数和边数
tree = {}
for _ in range(m):
   x, y = map(int, input().split())  # x是y的父节点
   if x not in tree:
       tree[x] = []
   tree[x].append(y)

# 输出结果
root = find_root(tree)
max_node = find_max_children(tree)
children = find_children(tree, max_node)

print(root)
print(max_node)
print(" ".join(map(str, children)))

 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区