HDU 1166 敌兵布阵 (树状数组--单点更新,区间求值)

本文详细解析了一个基于树状数组的OJ题目,提供了清晰的题意解释、解题思路及通过的AC代码实现。重点强调了树状数组的应用场景及关键操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OJ题目 : click here ~~~

中文的,大概题意就不说了。树状数组的水题。

忘记清空数组,导致WA,真可恨啊~~~~~~~哭

AC_CODE

int n;
int num[50002];

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

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

void add(int x , int d)
{
    while(x <= n)
    {
        num[x] += d;
        x += lowbit(x);
    }
}

int main()
{
    int Case;
    cin >> Case;
    for(int cas = 1;cas <= Case;cas++)
    {
        printf("Case %d:\n",cas);
        memset(num , 0 , sizeof(num));//为什么这个总是会忘记。。
        scanf("%d",&n);
        int i , j , a , b;
        for(i = 1;i <= n;i++)
        {
            scanf("%d",&a);
            add(i , a);
        }

        string command;
        while(cin >> command)
        {
            if(command == "Query")
            {   scanf("%d%d",&a,&b);
                printf("%d\n",sum(b) - sum(a - 1));
            }
            else if(command == "Add")
            {
                scanf("%d%d",&a,&b);
                add(a , b);
            }
            else if(command == "Sub")
            {
                scanf("%d%d",&a,&b);
                add(a , -b);
            }
            else if(command == "End")
                break;
            
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值