Luogu P3374 【模板】树状数组 1

  真正的模板题。

  树状数组的思想很简单(不如说背代码更简单),每个节点记录多个节点的信息(每个点存x&(-x)个)。

  道理可以参见很多大佬的博客,最后前缀和的思想搞一下就好了。不想说也不会说。

  CODE

#include<cstdio>
using namespace std;
typedef long long LL;
const int N=500005;
LL tree[N],n,q,i,c,x,y;
inline void read(LL &x)
{
    x=0; char ch=getchar(); int flag=1;
    while (ch<'0'||ch>'9') { if (ch=='-') flag=-1; ch=getchar(); }
    while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    x*=flag;
}
void write(LL x)
{
    if (x/10) write(x/10);
    putchar(x%10+'0');
}
inline int lowbit(LL x) { return x&(-x); }
inline void add(LL x,LL y)
{
    while (x<=n)
    {
        tree[x]+=y;
        x+=lowbit(x);
    }
}
inline LL sum(LL x)
{
    LL tot=0;
    while (x)
    {
        tot+=tree[x];
        x-=lowbit(x);
    }
    return tot;
}
int main()
{
    read(n); read(q);
    for (i=1;i<=n;++i)
    read(x),add(i,x);
    while (q--)
    {
        read(c); read(x); read(y);
        if (c==1) add(x,y); else write(sum(y)-sum(x-1)),putchar('\n');
    }
    return 0;
}

 

  其实我是想用线段树再打一遍的,然后发现建树都不会打了。

  明天看线段树+Lazy Tag

  (Tarjan真放下周)

posted @ 2017-11-30 20:25  空気力学の詩  阅读(178)  评论(0编辑  收藏  举报