Leetcode 3786. Total Sum of Interaction Cost in Tree Groups

  • [Leetcode 3786. Total Sum of Interaction Cost in Tree Groups](#Leetcode 3786. Total Sum of Interaction Cost in Tree Groups)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题是Leetcode周赛481的第四题,是一道hard难度的题目。

这一题我没有自己搞定,是看了一下大佬的解题方法搞定的。

这一题的核心是需要转换一下思路,不是两两去考虑任意两个点的距离,而是去考虑任意一条边会被多少条满足条件的路径使用到。

此时,我们就可以通过图遍历的方式考察任意一条边下游的子树当中每一个group各自有多少个节点,此时,剩余所有的属于该group的节点要与之相连的话都需要经过这条边。

由此,我们就可以给出python代码实现了。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def interactionCosts(self, n: int, edges: List[List[int]], group: List[int]) -> int:
        graph = defaultdict(list)
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)

        total = Counter(group)
        ans = 0
        
        def dfs(u, fa):
            nonlocal ans
            cnt = defaultdict(int)
            cnt[group[u]] = 1
            for v in graph[u]:
                if v == fa:
                    continue
                subtree = dfs(v, u)
                for grp, _cnt in subtree.items():
                    ans += _cnt * (total[grp] - _cnt)
                    cnt[grp] += _cnt
            return cnt

        dfs(0, -1)
        return ans

提交代码评测得到:耗时712ms,占用内存109.22MB。

相关推荐
Espresso Macchiato1 个月前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
Espresso Macchiato1 个月前
Leetcode 3739. Count Subarrays With Majority Element II
leetcode hard·前序和数组·leetcode双周赛169·leetcode 3739
Espresso Macchiato2 个月前
Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array
leetcode·leetcode hard·容斥原理·leetcode 3729·leetcode周赛473·前序和数组
Espresso Macchiato2 个月前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471
Espresso Macchiato2 个月前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
Espresso Macchiato3 个月前
Leetcode 3700. Number of ZigZag Arrays II
动态规划·leetcode hard·矩阵乘法·leetcode 3700·leetcode周赛469
Espresso Macchiato3 个月前
Leetcode 3695. Maximize Alternating Sum Using Swaps
并查集·leetcode hard·dsu·uf·leetcode 3695·leetcode双周赛166
Espresso Macchiato5 个月前
Leetcode 3624. Number of Integers With Popcount-Depth Equal to K II
leetcode hard·segment tree·分段树·leetcode 3624·leetcode周赛459
Espresso Macchiato7 个月前
Leetcode 3563. Lexicographically Smallest String After Adjacent Removals
动态规划·leetcode hard·leetcode周赛451·leetcode 3563