【发布时间】:2022-01-17 17:25:50
【问题描述】:
给定一棵包含 N 个节点 (1-N) 的树,每个节点都有一个初始值 A[i]。树的根是节点1。
我们得到Q 类型的查询:
1 V X : multiply all nodes in subtree of `X` with value `V`.
2 X : find the value of node `X`.
约束:
N <= 10^5
Q <= 10^5
我的方法:
说,我们有下面的树作为输入:
1
/ \
2 3
/ \ \
4 5 7
/
6
The idea is to traverse the tree using **DFS** and construct a tree
traversal array that contains two values for each node.
index : 0 1 2 3 4 5 6
node : 1 2 4 6 5 3 7
subtree-size : 7 4 2 1 1 2 1
and then we create a `segment tree` using above array.
(0-6)
/ \
(0-3) (4-6)
/ \ / \
(0-1) (2-3) (4-5) (6)
/ \ / \ / \
(0) (1) (2) (3) (4) (5)
--> So now when we get a query of type-1 say, 1 3 2.
we need to multiply all nodes in 2's sub-tree, which means we need to do a update
query at (1-4) in our segment tree.
At each node of a segment tree we keep a initial multiplication factor as 1 and
update it by multiplying it with the value 'V (in this case = 3)' whenever we get the query of type 1.
--> When we get query of type - 2, say 2 4 : we can now query our
segment tree at (2, 2) and consolidate all the multiplication factors
in the path and multiply it with the existing value of node '4' to return the
result of the query.
使用这种方法,每个查询都可以使用时间O(log(n)) 来解决。我无法按时编写这种方法。
是否有任何其他更简单的方法来解决这个问题(可能不使用 seg-tree)并且根据约束查询时间应该至少与
O(log(n))时间一样有效。
【问题讨论】:
-
输入中树的边缘是如何编码的?
-
@trincot,边以列表的形式提供给我们:[(u1,v1), (u2, v2)....] 它不一定是二叉树。
-
请一次问一个问题。添加语言标签,并以该语言显示您迄今为止所做的工作。
-
@MadPhysicist,正如我所说,我无法编写完整的方法,但我已经在问题中描述了我的方法。
-
您过去曾问过几个答案很好的问题,但没有答案被标记为已接受。这是有原因的吗?
标签: algorithm math optimization data-structures segment-tree