To solve this problem efficiently, we need a data structure that allows us to perform range updates and queries on paths in a tree. We will use a combination of Heavy-Light Decomposition (HLD) and a Segment Tree with lazy propagation to achieve this.
Here’s a step-by-step explanation of the solution:
-
Heavy-Light Decomposition (HLD):
- HLD breaks the tree into multiple paths (chains). It helps in reducing the problem of path queries and updates in a tree to range queries and updates on an array.
- Each node in the tree is assigned a unique index according to the traversal order in HLD.
-
Segment Tree with Lazy Propagation:
- We build a segment tree over the array formed by HLD.
- We store additional information in each node of the segment tree:
sum: The sum of p_i in the range.
max: The maximum p_i in the range.
min: The minimum p_i in the range.
- We implement custom lazy propagation to handle both range maximum and minimum updates efficiently.
-
Handling Updates:
- For Type 1 Updates (
p_i = max(p_i, c_s)):
- If the maximum value in the current segment is less than or equal to
c_s, all values need to be updated to c_s.
- If the minimum value in the current segment is greater than or equal to
c_s, no updates are needed.
- Otherwise, we recursively push the updates to the children nodes.
- For Type 2 Updates (
p_i = min(p_i, c_s)):
- Similar logic applies, but with minimum and maximum values inverted.
-
Handling Queries:
- For Type 3 Queries (sum queries along a path):
- We decompose the path between two nodes into O(log N) segments using the HLD paths.
- We perform sum queries on these segments and accumulate the results.
-
Time Complexity:
- Preprocessing (HLD and segment tree building): O(N)
- Each query: O(log^2 N) (because each path can be broken down into O(log N) segments, and each segment operation is O(log N))
- Total time complexity: O((N + Q) * log^2 N), which is acceptable for N, Q ≤ 1e5.
Now, let's proceed to the actual implementation of this solution.
from sys import setrecursionlimit
import threading
import sys
def main():
import sys
sys.setrecursionlimit(1 << 25)
n, q = map(int, sys.stdin.readline().split())
tree = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
tree[a].append(b)
tree[b].append(a)
p = list(map(int, sys.stdin.readline().split()))
assert len(p) == n
# HLD variables
size = [0] * n
depth = [0] * n
parent = [0] * n
heavy = [ -1 ] * n
head = [0] * n
pos = [0] * n
current_pos = [0] # [list], since we need to modify it in dfs
def dfs(u, p_u):
size[u] = 1
max_subtree_size = 0
for v in tree[u]:
if v != p_u:
parent[v] = u
depth[v] = depth[u] + 1
dfs(v, u)
size[u] += size[v]
if size[v] > max_subtree_size:
max_subtree_size = size[v]
heavy[u] = v
def decompose(u, h):
head[u] = h
pos[u] = current_pos[0]
current_pos[0] += 1
if heavy[u] != -1:
decompose(heavy[u], h)
for v in tree[u]:
if v != parent[u] and v != heavy[u]:
decompose(v, v)
dfs(0, -1)
decompose(0, 0)
# Build segment tree
class SegmentTreeNode:
__slots__ = ['l', 'r', 'left', 'right', 'sum', 'max', 'min', 'to_update']
def __init__(self, l, r):
self.l = l
self.r = r
self.left = None
self.right = None
self.sum = 0
self.max = 0
self.min = 0
self.to_update = None # (type, value)
N = n
segment_tree = [0] * (4 * N)
arr = [0] * N
for i in range(n):
arr[pos[i]] = p[i]
def build(node, l, r):
if l == r:
node.sum = arr[l]
node.max = arr[l]
node.min = arr[l]
return
mid = (l + r) // 2
node.left = SegmentTreeNode(l, mid)
node.right = SegmentTreeNode(mid + 1, r)
build(node.left, l, mid)
build(node.right, mid + 1, r)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
root = SegmentTreeNode(0, N - 1)
build(root, 0, N - 1)
def push(node):
if node.to_update is not None:
t, val = node.to_update
if t == 1: # max
if node.max >= val:
node.min = max(node.min, val)
node.max = max(node.max, val)
node.sum = (node.r - node.l + 1) * val
if node.l != node.r:
node.left.to_update = (1, val)
node.right.to_update = (1, val)
elif node.min >= val:
# All values already >= val, do nothing
pass
else:
# Need to push down
push(node.left)
push(node.right)
node.left.to_update = (1, val)
node.right.to_update = (1, val)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
elif t == 2: # min
if node.min <= val:
node.min = min(node.min, val)
node.max = min(node.max, val)
node.sum = (node.r - node.l + 1) * val
if node.l != node.r:
node.left.to_update = (2, val)
node.right.to_update = (2, val)
elif node.max <= val:
# All values already <= val, do nothing
pass
else:
# Need to push down
push(node.left)
push(node.right)
node.left.to_update = (2, val)
node.right.to_update = (2, val)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
node.to_update = None
def range_update(node, l, r, t, val):
push(node)
if node.r < l or node.l > r:
return
if l <= node.l and node.r <= r:
if t == 1: # max update
if node.max >= val:
if node.min >= val:
# All >= val, do nothing
return
elif node.max <= val:
# All <= val, set all to val
node.sum = (node.r - node.l + 1) * val
node.max = val
node.min = val
if node.l != node.r:
node.left.to_update = (1, val)
node.right.to_update = (1, val)
else:
# Need to push down
range_update(node.left, l, r, t, val)
range_update(node.right, l, r, t, val)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
else:
# All < val, set all to val
node.sum = (node.r - node.l + 1) * val
node.max = val
node.min = val
if node.l != node.r:
node.left.to_update = (1, val)
node.right.to_update = (1, val)
else: # min update
if node.min <= val:
if node.max <= val:
# All <= val, do nothing
return
elif node.min >= val:
# All >= val, set all to val
node.sum = (node.r - node.l + 1) * val
node.max = val
node.min = val
if node.l != node.r:
node.left.to_update = (2, val)
node.right.to_update = (2, val)
else:
# Need to push down
range_update(node.left, l, r, t, val)
range_update(node.right, l, r, t, val)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
else:
# All > val, set all to val
node.sum = (node.r - node.l + 1) * val
node.max = val
node.min = val
if node.l != node.r:
node.left.to_update = (2, val)
node.right.to_update = (2, val)
return
range_update(node.left, l, r, t, val)
range_update(node.right, l, r, t, val)
node.sum = node.left.sum + node.right.sum
node.max = max(node.left.max, node.right.max)
node.min = min(node.left.min, node.right.min)
def range_query(node, l, r):
push(node)
if node.r < l or node.l > r:
return 0
if l <= node.l and node.r <= r:
return node.sum
return range_query(node.left, l, r) + range_query(node.right, l, r)
def path_query(u, v):
res = 0
while head[u] != head[v]:
if depth[head[u]] < depth[head[v]]:
u, v = v, u
h = head[u]
res += range_query(root, pos[h], pos[u])
u = parent[h]
if depth[u] > depth[v]:
u, v = v, u
res += range_query(root, pos[u], pos[v])
return res
def path_update(u, v, t, val):
while head[u] != head[v]:
if depth[head[u]] < depth[head[v]]:
u, v = v, u
h = head[u]
range_update(root, pos[h], pos[u], t, val)
u = parent[h]
if depth[u] > depth[v]:
u, v = v, u
range_update(root, pos[u], pos[v], t, val)
results = []
for _ in range(q):
data = sys.stdin.readline().split()
if not data:
data = sys.stdin.readline().split()
if not data:
continue
t = int(data[0])
if t == 1:
ai, bi, ci = map(int, data[1:])
ai -= 1
bi -= 1
path_update(ai, bi, 1, ci)
elif t == 2:
ai, bi, ci = map(int, data[1:])
ai -= 1
bi -= 1
path_update(ai, bi, 2, ci)
elif t == 3:
ai, bi = map(int, data[1:])
ai -= 1
bi -= 1
res = path_query(ai, bi)
results.append(str(res))
else:
# Should not happen
pass
print('\n'.join(results))
threading.Thread(target=main).start()