版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LSC_333/article/details/91369433
题目大意
给一棵树,求从根节点到叶子节点的权值和是给定的 的路径
输入
每组包含一个测试用例
第一行是
表示树的节点数,
表示非叶子节点数,
表示所给的和
第二行有
个正数表示每个节点的权值,且权值都小于1000
之后有
行,表示每个非叶子节点的信息,格式为ID K ID[1] ID[2] ... ID[K]
,ID
表示节点的编号,K
表示子节点数,之后跟着K
个数表示每个子节点的编号,所有编号都是一个两位数字
输出
对每个样例,如果路径不止一条就以非递减的顺序输出路径权值
非递减:序列
大于序列
,当且仅当存在
使得
(
)并且
样例输入
20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19
样例输出
10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2
解析
这题就是树的遍历,从树的根节点遍历到叶子节点,同时计算权值和,在输入的时候将子节点按照权值降序排列,这样在搜索时就会按照要求的顺序输出每条符合题意的路径
# -*- coding: utf-8 -*-
# @Time : 2019/6/10 11:23
# @Author : ValarMorghulis
# @File : 1053.py
class node:
def __init__(self, weight):
self.weight = weight
self.child = list()
def toString(self):
return "weight:%d\n" % self.weight + str(self.child)
tree = list()
n, m, s = 0, 0, 0
path = list()
def dfs(root, sum):
global path
if sum > s:
return
if sum == s:
if tree[root].child:
return
for i in range(len(path)):
print("%d" % path[i], end=('\n' if i == len(path) - 1 else ' '))
return
for i in range(len(tree[root].child)):
path.append(tree[tree[root].child[i]].weight)
dfs(tree[root].child[i], sum+tree[tree[root].child[i]].weight)
path.pop()
def solve():
global n, m, s, tree, path
n, m, s = map(int, input().split())
w = list(map(int, input().split()))
for i in range(n):
t = node(w[i])
tree.append(t)
for i in range(m):
line = list(map(int, input().split()))
id = line[0]
tree[id].child = line[2:]
tree[id].child = sorted(tree[id].child, key=lambda x: tree[x].weight, reverse=True)
path.append(tree[0].weight)
dfs(0, tree[0].weight)
if __name__ == "__main__":
solve()