`(i&(i + 1))-1`是什么意思?(在芬威克树中)

StackExchange123

在学习Fenwick树时,我发现了此实现:

资料来源:https : //algorithmist.com/wiki/Fenwick_tree

class Fenwick_Tree_Sum
{
    vector<int> tree;
    Fenwick_Tree_Sum(const vector<int>& Arg)//Arg is our array on which we are going to work
    {
        tree.resize(Arg.size());
        
        for(int i = 0 ; i<tree.size(); i++)
            increase(i, Arg[i]);
        
    }

    // Increases value of i-th element by ''delta''.
    void increase(int i, int delta)
    {
        for (; i < (int)tree.size(); i |= i + 1)
            tree[i] += delta;
    }

    // Returns sum of elements with indexes left..right, inclusive; (zero-based);
    int getsum(int left, int right)
    {
        return sum(right) - sum(left-1); //when left equals 0 the function hopefully returns 0
    }

    int sum(int ind)
    {
        int sum = 0;
        while (ind>=0)
        {
            sum += tree[ind];
            ind &= ind + 1;
            ind--;
        }
        return sum;
    }
};

我可以在代码中看到i |= i + 1ind &= ind + 1; ind--

我知道i |= i + 1只是设置下一个未设置的位。

但是,(i & (i + 1)) - 1实际上是做什么的呢?

这里有些例子:

-------------------------------------
         i        | (i & (i + 1)) - 1
-------------------------------------
  0 - 0000000000  |  -1 - 1111111111
  1 - 0000000001  |  -1 - 1111111111
  2 - 0000000010  |   1 - 0000000001
  3 - 0000000011  |  -1 - 1111111111
  4 - 0000000100  |   3 - 0000000011
  5 - 0000000101  |   3 - 0000000011
  6 - 0000000110  |   5 - 0000000101
  7 - 0000000111  |  -1 - 1111111111
  8 - 0000001000  |   7 - 0000000111
  9 - 0000001001  |   7 - 0000000111
 10 - 0000001010  |   9 - 0000001001
 11 - 0000001011  |   7 - 0000000111
 12 - 0000001100  |  11 - 0000001011
 13 - 0000001101  |  11 - 0000001011
 14 - 0000001110  |  13 - 0000001101
 15 - 0000001111  |  -1 - 1111111111
 16 - 0000010000  |  15 - 0000001111
 17 - 0000010001  |  15 - 0000001111
 18 - 0000010010  |  17 - 0000010001
 19 - 0000010011  |  15 - 0000001111
 20 - 0000010100  |  19 - 0000010011
 21 - 0000010101  |  19 - 0000010011
 22 - 0000010110  |  21 - 0000010101
 23 - 0000010111  |  15 - 0000001111
 24 - 0000011000  |  23 - 0000010111
 25 - 0000011001  |  23 - 0000010111
 26 - 0000011010  |  25 - 0000011001
 27 - 0000011011  |  23 - 0000010111
 28 - 0000011100  |  27 - 0000011011
 29 - 0000011101  |  27 - 0000011011
 30 - 0000011110  |  29 - 0000011101
我的天啊

如果该位模式i就像是...0111,的位模式i+1...1000因此,i & (i+1)均值i - 2^{number of leading ones}并将所有前导1s转换为零。例如,如果i是,i & (i+1)则等于i另一方面,-1意味着将所有前导零转换为1(包括上一步的所有前导零为零)并将连续1的零转换为零。

这样做的-1下一步,i & (i+1)将降低i2^{leading 1's and zeros after 1's}的前值i

是什么原因?它有助于表明找到累积总和的时间复杂性将O(log n)在最坏的情况下发生。

为了找到这个计算背后的原因,你需要关注每个节点上i会负责计算指数i(i - (1 << r) + 1并且“r表示索引中设置的最后1位i”。为了找到对应于指数总和i,我们需要从总结所有相关的值0i注意,由于指定的属性,我们不需要对所有索引求和。因此,我们需要总结指数ii - (1 << r)......等等等等。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章