AcWing 树形DP相关问题 1075. 数字转换

import sys
sys.stdin = open('data.txt', 'r')

'''
树形DP, 树的最长路径的应用, 求一个森林里面所有树的最长路径的最大值
'''

N = int(input())

# 先求所有值的约数
factor = {}
for i in range(1, N+1):
    for j in range(2, N // i + 1):  # 约数不能是自己,所以从2开始枚举,如果约数可以是自己,从1开始枚举
        if i*j not in factor:
            factor[i*j] = []
        factor[i*j].append(i)

link = {}
all_roots = set()
for x in factor:
    y = sum(factor[x])
    if y < x:
        if y not in link:
            link[y] = []
        link[y].append(x)
        if y not in all_roots:
            all_roots.add(y)
        if x in all_roots:
            all_roots.remove(x)

ans = [0]  # 定义单独一个点也是有路径的,路径长度是1, 全局最大值就初始化为1

def dfs(root, prev=None):
    # 最大值和次大值
    max1, max2 = 0, 0 # 最大值和次大值初始值设置为0, 可以直接避免掉负边带来的负面影响,默认可以看做每个节点都连接了无数个隐性的空节点,且边全权为0

    if root in link:
        for child in link[root]:
            if child == prev:
                continue

            max_len = dfs(child, root) + 1
            if max_len > max1:
                max2 = max1
                max1 = max_len
            elif max_len > max2:
                max2 = max_len

    ans[0] = max(ans[0], max1 + max2)
    return max1

for root in all_roots:
    dfs(root)

print(ans[0])





猜你喜欢

转载自blog.csdn.net/xiaohaowudi/article/details/107762057
今日推荐