博客
关于我
DP/数论 - 树形DP - 数字转换
阅读量:369 次
发布时间:2019-03-04

本文共 1266 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要构建一个树结构,其中每个数 x 都与其约数之和 sum[x] 相连(前提是 sum[x] < x)。然后,我们需要找到这个树中最长路径的长度。

方法思路

  • 计算约数之和:对于每个数 x,计算其所有约数之和 sum[x]。我们可以使用高效的方法来计算这个值,例如反向遍历的方法。
  • 构建邻接表:根据 sum[x] < x 的条件,构建每个数 x 的邻接表。
  • 深度优先搜索 (DFS):从数 1 出发,进行一次 DFS,找到从 1 出发的最长路径。由于所有数都连接到 1 的连通块,这个路径很可能是整个图的最长路径。
  • 解决代码

    import sysfrom collections import dequedef main():    sys.setrecursionlimit(1 << 25)    n = int(sys.stdin.readline())    sum_num = [0] * (n + 1)    for i in range(1, n + 1):        for j in range(2, n // i + 1):            sum_num[i * j] += i    adj = [[] for _ in range(n + 1)]    for x in range(1, n + 1):        s = sum_num[x]        if s < x and s <= n:            adj[x].append(s)            adj[s].append(x)    visited = [False] * (n + 1)    max_path = 0    q = deque()    q.append((1, 0))    visited[1] = True    while q:        u, d = q.popleft()        if d > max_path:            max_path = d        for v in adj[u]:            if not visited[v]:                visited[v] = True                q.append((v, d + 1))    print(max_path)if __name__ == "__main__":    main()

    代码解释

  • 计算约数之和:使用双重循环遍历每个数 i 和其倍数 j,累加 i 到 sum_num[j] 中。
  • 构建邻接表:根据 sum_num[x] < x 的条件,构建每个数 x 的邻接表。
  • 广度优先搜索 (BFS):从数 1 开始,使用 BFS 遍历图,记录每个节点的访问状态,并计算最长路径的长度。
  • 这种方法高效地处理了约数之和的计算,并通过 BFS 确保找到最长路径。代码能够在较大的 n 值下高效运行,满足题目要求。

    转载地址:http://epor.baihongyu.com/

    你可能感兴趣的文章
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>