[置顶] 树状数组

http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees 超级讲解,


hdu1166 敌兵布阵

单点修改, 区间查询, (区间和)

const int maxn=50000+123;
int a[maxn], c[maxn];
int n;

int sum(int x)
{
    for (int res=0; ; res+=c[x], x-=lowbit(x))if(x==0)return res;
}

void add(int x, int v)
{
    for (;x<=n; x+=lowbit(x))c[x]+=v;
}

void build()
{
    clean(c, 0);
    for (int i=1; i<=n; ++i) add(i, a[i]);
}

int main ()
{
    int t; scanf("%d", &t);
    for (int I=1; I<=t; ++I)
    {
        scanf("%d", &n);
        for (int i=1; i<=n; ++i) scanf("%d", a+i);
        build();
        char op[10];
        printf("Case %d:\n", I);
        while(scanf("%s", op))
        {
            if(op[0]=='E')break;
            int a, b; scanf("%d%d", &a, &b);
//            printf("%d %d\n", lowbit(a), lowbit(b));
//            printf("%d %d\n", sum(a), sum(b));

            if(op[0]=='Q')
                printf("%d\n", sum(b)-sum(a-1));
            if(op[0]=='A')add(a, b);
            if(op[0]=='S')add(a, -b);
        }
    }
    return 0;
}

http://codeforces.com/problemset/problem/216/C

区间更新, 单点查询, 别人都是暴力过的, 我用树状数组却错了, 不相信爱情了。。。

ll C[2*maxn];
int N;
int Query(int x)
{
    for (int res=0; ; res+=C[x], x-=lowbit(x))if(x==0)return res;
}

void Update(int x, int v)
{
    for (;x<=N; x+=lowbit(x))C[x]+=v;
}

void IUpdate(int s, int t, int v)
{
    Update(t+1, -v);
    Update(s, v);
}

int ans[10000+123];
int total;

int main ()
{
    int n, m, k;
    while (~scanf("%d%d%d", &n, &m, &k))
    {
        N=(n+m)<<1;
        total=0;
        clean(C, 0);
        for (int i=1; i<=n+m; ++i)
        {
            int t=k-Query(i);
//            for (int j=1; j<=n+m; ++j)printf("%d ", Query(j));
//            printf("Q=%d D=%d\n", t, i);
//            t=k-Query(i);
            for (int j=0; j<t; ++j)
            {
                ans[total++]=i;
                IUpdate(i, i+n-1, 1);
                ///IUpdate(i+n+m, i+n-1+n+m, 1);
            }
//            printf("%d %d\n", Query(i+1), i+1);
            if(Query(i+1)==0)IUpdate(i, i+n-1, 1), ans[total++]=i;
//            printf("%d %d\n", Query(i+1), i+1);
        }
        printf("%d\n", total);
        for(int i=0; i<total; ++i)
        {
            printf("%d ", ans[i]);
        }
        puts("");
    }
    return 0;
}



你可能感兴趣的:(c,Build)