We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Advanced
- Easy Addition
- Discussions
Easy Addition
Easy Addition
Sort by
recency
|
8 Discussions
|
Please Login in order to post a comment
To solve this problem efficiently, we can use a data structure called a segment tree. A segment tree is a binary tree that represents an array. This is the ninja moba way to solve this problem. Each node of the segment tree stores the sum of a range of elements from the original array.
Here's how we can approach the problem using a segment tree:
Create an adjacency list to represent the tree based on the given edges.
Build the segment tree using the adjacency list and assign initial values of zero to all nodes.
Process the update queries:
For each update query, traverse the path from node A to node B using a depth-first search (DFS) or any other graph traversal algorithm. Update the segment tree nodes along the path by adding the value (a1 + distance * d1) to each node, where the distance is the distance from the current node to node A. Repeat the above step for each update query. Process the retrieval queries:
For each retrieval query, traverse the path from node i to node j using a DFS or any other graph traversal algorithm. Calculate the sum of the values in the segment tree nodes along the path. Take the modulo 1000000007 of the sum and output the result. Here's the implementation in Python:
C++ Solution
for complete solution in python java c++ and c programming search for programs.programmingoneonone.com on google
I can't find how the query between the sum of weights between 5 and 3 is 9. The path would be 5,4,1,3 and the second path is 5,4,2,1,3. Why the longer path considered a solution?
the problem could be more interesting if the queries are done in random order... a hld aproach will be necesary...