BIT: Unable to understand update operation in Binary index Tree

情到浓时终转凉″ 提交于 2019-12-08 05:21:01

问题


I have just read answer on this question and was very satisfied and it is indeed a fantastic answer. It taught me the working of BIT.

But at the end, the second last paragraph is where I am struggling. It says,

Similarly, let's think about how we would do an update step. To do this, we would want to follow the access path back up to the root, updating all nodes where we followed a left link upward. We can do this by essentially doing the above algorithm, but switching all 1's to 0's and 0's to 1's. But if I see, take some example, it does not work just as by simply switching 1's and 0's, according to me.

e.g. lets take we want to update value at node 5 = 101 Switching 1s and 0s, we get 010... Now applying the procedure they have given earlier, we will end up updating some other node or so.

I must be getting it wrong. Please correct me.

Thank you in advance.


回答1:


I think you are right. Use this:

                     1
               /           \
         2                      3
      /      \                /     \
   4           5           6          7
 /   \       /   \       /   \       /  \
8     9    10    11    12    13    14    15

Functions:

int root(int node_index) { return node_index >> 1 }

int left(int node_index) { node_index << 1 }

int right(int node_index) { left(node_index) | 1 }



来源:https://stackoverflow.com/questions/28396696/bit-unable-to-understand-update-operation-in-binary-index-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!