树状数组 做题笔记1

HDU - 1166 敌兵布阵:

#include 
using namespace std;
int a[50005];
char cmd[1005];
int main()
{
    int t, n, m, i, j, k, ca = 1;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(i = 0; i <= n; i++)a[i] = 0;
        for(i = 1; i <= n; i++)
        {
            scanf("%d", &k);
            for(j = i; j <= n; j += j & -j)a[j] += k;
        }
        printf("Case %d:\n", ca++);
        while(scanf("%s", cmd) != EOF)
        {
            if(cmd[0] == 'E')break;
            else if(cmd[0] == 'Q')
            {
                int l, r;
                scanf("%d %d", &l, &r);
                int ans1 = 0, ans2 = 0;
                for(i = r; i > 0; i -= i & -i)ans1 += a[i];
                for(i = l - 1; i > 0; i -= i & -i)ans2 += a[i];
                printf("%d\n", ans1 - ans2);
            }
            else if(cmd[0] == 'A')
            {
                int x, y;
                scanf("%d %d", &x, &y);
                for(;x <= n; x += x & -x)a[x] += y;
            }
            else
            {
                int x, y;
                scanf("%d %d", &x, &y);
                for(;x <= n; x += x & -x)a[x] -= y;
            }
        }
    }
    return 0;
}

 

你可能感兴趣的:(树状数组)