树状数组

还是很懵逼 慢慢来
#include <stdio.h>
int lowbit(int n)
{
    return n&-n;
}

int bitTree[512];

int sum(int pos)
{
    int result = 0;
    for (int i = pos; i >0; )
    {
        result += bitTree[i];
        i = i - lowbit(i);
    }
    return result;
}

int add(int pos, int num)
{
    for (int i = pos; i <= 20; i+=lowbit(i))
    {
        bitTree[i] += num;
    }
    return true;
}

int main()
{
    int a[21] = {0};
    for (int  i = 1; i <= 20; i++)
    {
        a[i] = i;
        add(i, i);
    }
    for (int i = 1; i <= 20; i++)
    {
        printf("%d ", sum(i));
    }
    printf("\n");

    return 0;
}
阅读更多

没有更多推荐了,返回首页