树状数组--代码模板

  • 用树状数组,在存数据的时候下标应该是从1开始的;
  • 再求区间的和的时候和前缀和一样开始的下标是要减一的;
  • toSum(int x)中再求前缀和的时候是倒着向前走的;

   树状数组讲解:http://www.cnblogs.com/jinkun113/p/4725420.html    ORZorzorz一看就明白了

//树状数组修改值,求某区间的和
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <string>
#include <deque>
#include <map>
#define INF 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int a[maxn],c[maxn];
int T,n;

int lowbit(int x)
{
    return x & -x;
}

void upDate(int i, int x)
{
    while(i <= n)
    {
        c[i] += x;
        i += lowbit(i)
    }
}

int toSum(int x)
{
    int sum = 0;
    while(x > 0)
    {
        sum += c[x];
        x -= lowbit(x);
    }
    return sum;
}

int getSum(int st,int en)
{
    return toSum(en) - toSum(st - 1);
}




int main()
{
    memset(a, 0, sizeof(a));
    memset(c, 0, sizeof(c));
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d",&a[i]);
            upDate(i, a[i]);//修改i位置的值
        }
        int st,en;
        scanf("%d%d",&st,&en);
        printf("%d\n",getSum(st, en));//输出st到en之间的和
    }
    return 0;
}

 


版权声明:本文为sykai1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。