二进制索引树:如何找到索引与给定的累积频率索引、频率

2023-09-11 05:04:01 作者:人来狗往好不热闹

我试图找到一个二进制索引树(BIT)给定的累积频率的索引。

我可以用二进制搜索的帮助和一个函数计算累积频率在任何指标落实到解决O此问题(的log(n)*的log(n))。

不过,我想为O解决这个问题(的log(n))的。

所以,请帮助。

解决方案

该算法从的顶部codeR教程展示如何找到一个给定的累积频率在澳最大的指数(LOGN):

  

查找索引与给定cumultive频率的天真和最简单的解决方案仅仅是简单地通过所有指标迭代,计算累积频率,并检查它是否等于给定值。如果负频率它是唯一的解决办法。但是,如果我们有我们的树只有非负的频率(这意味着累积频率更大的索引不小),我们可以计算出对数的算法,这是二进制搜索的改进。我们经历的所有位(从最高的一个)上,进行索引,比较当前索引的累积频率与给定的值,并根据该结果,取区间(的较高或较低的一半就像在二进制搜索)。

  //如果在树中存在多个索引有相同
//累积频率,这个过程将返回
//一个最伟大
INT findG(INT cumFre){
    INT IDX = 0;

    而((位掩码= 0)及!及(IDX&所述; MaxVal最大值)){
        INT tIdx = IDX +位掩码;
        如果(cumFre> =树[tIdx]){
            //如果目前的累积频率等于cumFre,
            //我们仍在寻找更高的索引(如果存在)
            IDX = tIdx;
            cumFre  -  =树[tIdx]
        }
        BITMASK>> = 1;
    }
    如果(cumFre!= 0)
        返回-1;
    其他
        返回IDX;
}
 

基于C语言的二进制查找树 源码

I was trying to find the Index with a given cumulative frequency in a Binary Indexed Tree (BIT).

I was able to solve this problem in O(log(n)*log(n)) by implementing it with the help of binary search and a function which calculates the Cumulative frequency at any index.

But I was thinking of solving this problem in O(log(n)).

So please help.

解决方案

This algorithm from a topcoder tutorial shows how to find the greatest index with a given cumulative frequency in O(logn):

The naive and most simple solution for finding an index with a given cumultive frequency is just simply iterating through all indexes, calculating cumulative frequency, and checking if it's equal to the given value. In case of negative frequencies it is the only solution. However, if we have only non-negative frequencies in our tree (that means cumulative frequencies for greater indexes are not smaller) we can figure out logarithmic algorithm, which is modification of binary search. We go through all bits (starting with the highest one), make the index, compare the cumulative frequency of the current index and given value and, according to the outcome, take the lower or higher half of the interval (just like in binary search).

// if in tree exists more than one index with a same
// cumulative frequency, this procedure will return 
// the greatest one
int findG(int cumFre){
    int idx = 0;

    while ((bitMask != 0) && (idx < MaxVal)){
        int tIdx = idx + bitMask;
        if (cumFre >= tree[tIdx]){ 
            // if current cumulative frequency is equal to cumFre, 
            // we are still looking for higher index (if exists)
            idx = tIdx;
            cumFre -= tree[tIdx];
        }
        bitMask >>= 1;
    }
    if (cumFre != 0)
        return -1;
    else
        return idx;
}