HDOJ 1166 敌兵布阵(线段树单点更新求区间和)

本文介绍了一种基于线段树的数据结构实现,用于高效处理数组的区间查询与更新操作。该实现通过递归构建和更新线段树节点,支持查询指定区间内的元素总和,并能快速增加或减少特定位置的元素值。


#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#define VN 50005
#define INT_MAX 0x3f3f3f3f
#define LL __int64
using namespace std;
int N, n, x, y, a, T, A[VN*3];
LL dat[VN*3];
char s[20];
void init(int n_)
{
    N = 1;
    while (N < n_) N *= 2;
    for (int i = 0; i < 2*N-1; i++) dat[i] = 0;
}
void update(int k, int a)
{
    k += N-1;
    dat[k] += a;
    while (k > 0)
    {
        k = (k - 1) / 2;
        dat[k] += a;
    }
}
LL query(int a, int b, int k, int l, int r)
{
    if (r <= a || b <= l) return 0;
    if (a <= l && r <= b) return dat[k];
    else
    {
        LL vl = query(a, b, k*2+1, l, (l+r) / 2);
        LL vr = query(a, b, k*2+2, (l+r) / 2, r);
        return vl+vr;
    }
}
int main()
{
    scanf("%d", &T);
    int cnt = 0;
    while (T--)
    {
        printf("Case %d:\n", ++cnt);
        scanf("%d", &n);
        init(n);
        memset(dat, 0, sizeof(dat));
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &A[i]);
            update(i, A[i]);
        }

        while (1)
        {
            scanf("%s", s);
            if (strcmp(s, "End") == 0) break;
            if (strcmp(s, "Query") == 0)
            {
                scanf("%d%d", &x, &y);
                LL ans = query(x-1 , y, 0, 0, N);
                printf("%I64d\n", ans);
            }
            if (strcmp(s, "Add") == 0)
            {
                scanf("%d%d", &x, &a);
                update(x-1, a);
            }
            if (strcmp(s, "Sub") == 0)
            {
                scanf("%d%d", &x, &a);
                update(x-1, -a);
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值