834. Sum of Distances in Tree

An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given.

The ith edge connects nodes edges[i][0] and edges[i][1] together.

Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes.

Example 1:

Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: 
Here is a diagram of the given tree:
  0
 / \
1   2
   /|\
  3 4 5
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.  Hence, answer[0] = 8, and so on.

Note: 1 <= N <= 10000

思路:直接BFS会TLE,优化degree为1的Node也TLE,接着想优化其他degree的Node,到此有点卡住

答案是建树,然后求出每个Node有多个子Node,这样只要求出res[root],求root的child的时候,就知道有count[child]个Node的距离拉近了,N-count[i]个Node的距离变远 了1,这样只要以原始root为起点做一遍BFS/DFS就可以了

class Solution(object):
    def sumOfDistancesInTree(self, n, edges):
        """
        :type N: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        from collections import defaultdict
        d = defaultdict(set)
        for s,t in edges: 
            d[s].add(t)
            d[t].add(s)
        
        count = [1]*n
        res = [0]*n
        
        # calculate from child to root
        def dfs(root, vis):
            vis.add(root)
            for i in d[root]:
                if i not in vis:
                    dfs(i, vis) 
                    # now count[i], res[i] is ready
                    # here res[i] means use i as root, sum of all children to i
                    # so, only res[init_root] is correct
                    count[root] += count[i]
                    res[root] += res[i] + count[i]
        
        # calculate from root to child
        def dfs2(root, vis):
            vis.add(root)
            for i in d[root]:
                if i not in vis:
                    res[i] = res[root] - count[i] + n-count[i]
                    dfs2(i, vis)
                    
        dfs(0, set())
        dfs2(0, set())
        return res
            
            
        
s=Solution()
print(s.sumOfDistancesInTree(n = 2, edges = [[0,1]]))
print(s.sumOfDistancesInTree(n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]))
        



def calculate_bow_vector(descriptor_matrix): kmeans = joblib.load("./model/kmeans.pkl") cluster_centers = kmeans.cluster_centers_ kdtree = KDTree(cluster_centers) mean_distance = calculate_mean_distance(cluster_centers) # 利用 kdtree 查询最近的 k个聚类中心 distances, indices = kdtree.query( descriptor_matrix, k=3, distance_upper_bound=0.7 * mean_distance) """ :param k: the number of nearest neighbors to return :param distance_upper_bound: return only neighbors within this distance :return: The distances to the nearest neighbors and The index of each neighbor """ print(distances) # 过滤掉距离超过阈值的点 filtered_distances = [] filtered_indices = [] for i in range(len(descriptor_matrix)): valid_data = distances[i] < 0.7 * mean_distance valid_index = indices[i][valid_data] valid_distance = distances[i][valid_data] filtered_indices.append(valid_index) filtered_distances.append(valid_distance) weights = 1.0 / (distances + 1e-8) weights /= np.sum(weights, axis=1, keepdims=True) """ :param keepdims: If this is set to True, the axes which are reduced are left in the result as dimensions with size one """ bow_matrix = np.zeros(shape=(descriptor_matrix.shape[0], cluster_centers.shape[0])) for i in range(descriptor_matrix.shape[0]): # np.bincount(..., minlength) 统计每个索引出现的次数,并确保输出数组的长度至少为 minlength print(np.bincount( indices[i], weights=weights[i], minlength=cluster_centers.shape[0]).shape) bow_vector = np.sum(bow_matrix, axis=0) print(bow_vector) # linalg=linear(线性) + algebra(代数), # norm 表示范数 -- 默认为欧几里得范数 print("--------------归一化处理--------------") print(bow_vector / np.linalg.norm(bow_vector))但是下面就都不对了,帮我修改一下
08-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值