I am confused about how to get sum from a node y to its ancestor x using a segment tree. there is query of 10^5 order consists of update and find sum of the nodes between them.!
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
I am confused about how to get sum from a node y to its ancestor x using a segment tree. there is query of 10^5 order consists of update and find sum of the nodes between them.!
Name |
---|
Auto comment: topic has been updated by PR_0202 (previous revision, new revision, compare).
Please link the problem.
This problem is a subproblem of another problem
You can link that. It’s good to link problems so people know they’re not helping with a problem from an ongoing contest.
what I did is doing some thing like prefix sum from the root node and for the sum I printed \n tree[y-1].second-tree[x-1].second
and for update I did this \n
void update(int y,int z){ tree[y].second+=z; for(int x: tree[y].first){ update(x,z); } } \n I am confused how to do this if O(long) time complexity please help me
Maintain an array which for every $$$i$$$ will store the sum of all the ancestors(including itself) in $$$array[i]$$$. Now to find the answer for $$$x$$$ and it's anscestor $$$y$$$ it would be equal to $$$array[x]$$$ — $$$array[parentOfY]$$$(similiar as we do in prefix sum from l to r).
Now coming to the update part. When a node value is updated, then what happens? Let $$$x$$$ is updated. Then only the nodes which are in the subtree of $$$x$$$(including itself) are affected, because $$$x$$$ can only be an ancestor of nodes in it's subtree or itself. So when when $$$x$$$ is update do a range update in it's subtree.
Suppose $$$x$$$ was holding value 10($$$a[x]$$$ not $$$array[x]$$$) earlier now it's an update and asks to change it to 5. since all the nodes in it's subtree were holding sum of all of it's ancestor which also includes $$$x$$$ so $$$5 - 10$$$ needs to be added to every nodes in subtree of $$$x$$$ incuding itself. For subtree update you can use preorder traversal.
Fenwick tree would be easier to use here.
But, subtree update if O(n)??
See this to flatten a tree into an array. Then for range update we are using fenwick tree or Segment tree so it will be O(log2(N)).
UPD: I just noticed that the above link answers a more general question and yours is a subset of that one if read it correctly.
Thank you so much brother!!
Yes..