题解 | #父子情深#
父子情深
http://www.nowcoder.com/practice/f5808fcdc1ea4398be4edcea6132c6d2
对于query中的节点我们记录其改变值,并通过bfs依次将其传递给下一层节点即可
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 从 1 到 n 每个结点的权值。
# @param n int
# @param Edge Point一维数组 (u, v) 集合
# @param q int
# @param Query Point一维数组 Point.x 为题中 r, Point.y为题中 v
# @return long一维数组
#
import collections
class Solution:
def solve(self , n , Edge , q , Query ):
# write code here
weight = [0] * (n + 1)
graph = collections.defaultdict(list)
for i in range(len(Edge)):
x,y = Edge[i].x,Edge[i].y
graph[x].append(y)
graph[y].append(x)
change = collections.defaultdict(int)
for i in range(len(Query)):
x,y = Query[i].x,Query[i].y
change[x] += y
queue = []
weight[1] += change[1]
queue.append([1,weight[1]])
visited = {1}
while queue:
cur,d = queue.pop(0)
for next_ in graph[cur]:
if next_ in visited:
continue
visited.add(next_)
weight[next_] += change[next_] + d
queue.append([next_,weight[next_]])
return weight[1:]
查看15道真题和解析