AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79450153
Accepted
Irina
Irina
Asked: 2025-02-19 12:07:13 +0800 CST2025-02-19 12:07:13 +0800 CST 2025-02-19 12:07:13 +0800 CST

这个算法 cuttree hackerrank 如何工作?

  • 772

给定一棵有 n 个节点的树 T,T 中有多少个子树 (T') 最多有 K 条边连接到 (T – T')? 输入格式

第一行包含两个整数 n 和 K,后面跟着 n-1 行,每行包含两个整数 a 和 b,表示 a 和 b 之间存在边。

约束

1 <= K <= n <= 50 每个节点都用从 1 到 n 的不同数字表示。

输出格式

一个整数,表示可能的子树的数量。

def cutTree(n, k, edges):
    g = [[] for _ in range(n)]
    for i in edges:
        g[i[0]-1].append(i[1]-1)
        g[i[1]-1].append(i[0]-1)
    global ans
    ans = 1
    def multiply(x, y):
        ans = defaultdict(lambda: 0)
        for k, v in x.items():
            for k1, v1 in y.items(): ans[k+k1-1] += v*v1
        for k, v in ans.items():
            if k in x: x[k] += v
            else: x[k] = v
    def dfs(i,p):
        global ans
        if g[i] == [p]:
            ans += 1
            return {0:1}
        x = 1 if i else 0
        res = {len(g[i])-x : 1}
        for nxt in g[i]:
            if nxt != p: multiply(res, dfs(nxt, i))
        ans += sum(((v if i+x <= k else 0) for i, v in res.items()))
        return res
    dfs(0,-1)
    return ans

它解决了https://www.hackerrank.com/challenges/cuttree/forum但是如何解决呢?

python
  • 1 1 个回答
  • 46 Views

1 个回答

  • Voted
  1. Best Answer
    Sharp Dev
    2025-02-19T14:20:26+08:002025-02-19T14:20:26+08:00

    这是我可以给您的解释(如果您需要澄清,请告诉我)。

    大意

    由于 T 的子树T′是一组连通的节点。
    想象一下从某个节点开始扩展这样的子树,然后针对每个相邻节点(DFS 树中的子节点)决定是否要附加它。
    如果不附加分支,则该边将被切断。

    观察结果

    1. 当您从子节点附加子树时,连接子节点和当前节点的边将从切割变为附加。
    2. 当组合来自不同分支的选择时,您需要为所附加的每个分支减去 1(因为您节省了一个切口)。

    动态规划

    代码使用动态规划来有效地计算不同分支的数量(是的,尽管 Hackerrank 论坛/讨论成员声称如此,但此代码使用的是底层 dp)。

    目前,代码创建了一个字典 dp 表,其中的键是子树(包括当前节点)具有的切边数量,值是实现该切边的方法数量。

    请注意,“乘法”函数结合了 dp 状态。例如:
    a)。假设您有一个当前配置,其中包含 k(edgeCount1)个边界边(来自当前节点的部分子树)和一个可以以产生 k1(edgeCount2)个边界边的方式连接的子子树。(再次注意我们正在保存 1 个切口的观察结果)
    2. 对边界边的可能数量的卷积可以被认为类似于将两个多项式(其中指数跟踪边界边的数量)相乘,移位为 -1。

    是什么让这段代码变得棘手

    作者让代码变得如此难以理解的原因之一是他们使用了名称糟糕的变量,在某些情况下,这些名称确实分散了人们对主要思想的注意力。因此,我提供了更新的代码(它简化了部分逻辑,但也以一种更容易理解代码的方式命名了变量):

    def cutTree(n, k, edges):
        graph = [[] for _ in range(n)]
        #We are creating an undirected graph from the edges
        for i in edges:
            graph[i[0]-1].append(i[1]-1)
            graph[i[1]-1].append(i[0]-1)
        global ans
        ans = 1
        #previously called multiply
        def combine(dp, dp2):
            counts = Counter()
            for edgeCount1, v in dp.items():
                #k (or edgeCount1) is the edgeCount
                #v is the number of times we can count/achieve that edgeCount
                for edgeCount2, v2 in dp2.items():
                    #You'll remember that y (dp2) is also part of dp
                    #k1 (edgeCount2) is edgeCount
                    #v1 (v2) is the number of times we can count/achieve that edgeCount
                    #we multiply to get the combinations
                    #again the observation is that we save 1 cut edge when combining
                    counts[edgeCount1+edgeCount2-1] += v*v2
            for edgeCount, v in counts.items():
                #add combinations to the edgeCount (k)
                dp[edgeCount]+=v
        def dfs(node,parent):
            global ans
            hasParent = 1 if node else 0
            #x is telling us if we have a parent.
            edgeCount = len(graph[node])-hasParent # Number of edges that aren't the parent.
            dp = Counter()
            dp[edgeCount] = 1 #edges: 1
            for nxt in graph[node]:
                #nxt not being equal to parent makes sure we don't revisit the parent.
                if nxt != parent: 
                    combine(dp, dfs(nxt, node))
            #If i (the edge count) + hasParent (which is 1 if there is a parent, and 0 otherwise)
            #In other words if the total edge count is less than or equal to  k (i.e. at most K edges)
            #We are going to add the number of times that combination happens (v), 
            #We discard edge counts that are too large
            ans += sum(((v if i+hasParent <= k else 0) for i, v in dp.items()))
            return dp
        dfs(0,-1) #start with node 0 parent -1 (no parent)
        return ans
    

    我的解释可能不够简洁(就简化而言),我鼓励其他人发布自己的答案来解释代码。
    希望我的示例代码和调整后的变量名能够稍微解释一下代码的作用

    (不过我想指出的是,我确实删除了 dfs 中的基线情况,因为没有必要……就解释而言,这可能是一个错误(因为可能更容易看到其他情况,或者您也可以尝试理解这一点)……

    我再次鼓励其他人发布他们的解释,如果您不理解其中的一部分,请随时发表评论。

    • 1

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve