上一次的节点选择算法由于春节过年耽搁了,现在重新补上
上篇链接:算法刷题系列(四)蓝桥杯python算法训练3
- 经验教训
在纷繁复杂的使用了列表来暂存数据之后,发现其实可以利用笔者自己不太常用的字典遍历来减少内存占用,于是更新代码为:
n = int(input())
weight_list =[0] + list(map(int, input().split()))
aix_dict = {}
for i in range(1, n + 1):
aix_dict[i] = []
for i in range(n - 1):
a, b = list(map(int, input().split()))
aix_dict[a].append(b)
aix_dict[b].append(a)
def deep_copy(temp_dict):
dic = {}
for key in temp_dict:
dic[key] = temp_dict[key]
return dic
def dp(temp_dict):
score = 0
for key in temp_dict:
dic = deep_copy(temp_dict)
for k in dic[key]:
if k in dic.keys():
del dic[k]
del dic[key]
temp_score = 0
if dic == {}:
temp_score = weight_list[key]
else:
temp_score = weight_list[key] + dp(dic)
if score
关注
打赏
热门博文
- 【Leetcode】剑指Offer 34:二叉树中和为某一值的路径
- 【Leetcode】剑指Offer 33:二叉搜索树的后序遍历序列
- 【Leetcode】剑指Offer 32-III: 从上到下打印二叉树 III
- 【Leetcode】剑指Offer 32-II: 从上到下打印二叉树 II
- 【Leetcode】剑指Offer 32-I:从上到下打印二叉树
- 【Leetcode】剑指Offer 31:栈的压入、弹出序列
- 【Leetcode】剑指Offer 30:包含min函数的栈
- 【Leetcode】剑指Offer 29:顺时针打印矩阵
- 【Leetcode】剑指Offer 28:对称的二叉树
- 【Leetcode】剑指Offer 27:二叉树的镜像