爷怎么这么可爱 2022-01-12 09:21 采纳率: 0%
浏览 26

蓝桥杯 结点选择只有70分

为什么蓝桥杯 结点选择只有70分
我用的python
是从网上抄的代码

def dfs(now,pre):
    global value,table
    # print('now',now)
    # print('pre',pre)
    for i in table.get(now):
        if i !=pre:
            dfs(i,now)
            # print('dfs完成!',now,i)
            value[now][0]+=max(value[i][0],value[i][1])
            value[now][1]+=value[i][0]
            # print(value[now][0],value[now][1])

n = int(input())
value = list(map(int, input().split()))
value = list(map(lambda x:[0,x],value))
value.insert(0,0)
# print(value)
table = {}
for i in range(n):
    table.update({i + 1: []})
for i in range(n - 1):
    father, child = list(map(int, input().split()))
    table.get(father).append(child)
    table.get(child).append(father)
# print(table)
dfs(3, 0)
print(max(value[3][0], value[3][1]))

  • 写回答

1条回答 默认 最新

  • bekote 2022-01-12 10:42
    关注

    你看看这行不行

    
    def dfs(tree, pre, f):
        value = 0
        for child in tree[pre]:
            value1 = dfs(tree, child, False)
            if not f:
                value2 = dfs(tree, child, True) + child
                if value2 > value1:
                    value1 = value2
            value += value1
        return value
        
        
    n = int(input())
    value = list(map(int, input().split()))
    tree = {}
    sroot = [i for i in range(1,n+1)]
    for i in range(n + 1):
        tree.update({i: []})
    for i in range(n - 1):
        father, child = list(map(int, input().split()))
        tree.get(father).append(child)
        if child in sroot:
            sroot.remove(child)
    tree[0] = sroot
    print(dfs(tree, 0, False))
     
    
    评论

报告相同问题?

问题事件

  • 创建了问题 1月12日

悬赏问题

  • ¥20 六子棋博弈基于Alpha-Beta剪枝搜索算法的优化
  • ¥15 mlx90393用stm32f1的单片机使用软件i2c通信一直报错
  • ¥50 使用MS Log Parser查询使用Bitvise SSH Server登录的IP
  • ¥20 校园二手交易小程序搭建
  • ¥15 请问在ubuntu用conda创建环境报错怎么能解决
  • ¥15 STM32CubeMX/proteus按键控制指示灯颜色切换
  • ¥20 python,计算区位熵和扩张指数
  • ¥15 Python环境配置
  • ¥15 解决页面无法编入索引:被“noindex”标签排除的问题?
  • ¥15 arduino测量电阻