Dfs, Fibonacci Numbers, Dynamic Programming
Given a rooted tree T (root = node 1) with N vertices (all containing value 0), Perform Q queries of the following type and output the final tree (nodes 1 to N).
U X A B: The character ‘U’ followed by 3 integers X A B
For each query, let f be defined as
For every node on the path from root to X (both inclusive):
Where level of root node is 1.
The problem does not require intermediate results, since we only need to calculate the final tree, we need to store some lazy values during update queries so that the final tree can be built by adding all queries at once.
The update queries are nothing but Fibonacci numbers with an offset (a,b). Kth term can be calculated as:
where fib represents the Fibonacci numbers starting with 0,1
Another observation that can be made is:
At every node, 2 values can be stored previous and current.
Add depth(i)th term of the given sequence in the node’s ‘current’.
Add (depth(i)+1)th term of the given sequence in the node’s ‘previous’.
After all queries:
The value to be added at the parent node can be calculated as child’s ‘previous’– child’s ‘current’.
A node can have multiple children and hence the expression would be:
Which can be re written as:
(C1Prev+ C2Prev+C3Prev+……+CnPrev)-(C1Cur+ C2Cur+C3Cur+……+ CnCur)
Hence, a final Dfs can be done to do the above calculations in O(n)
Author’s solution Solution