hdu1166敌兵布阵(大意)树状数组

本文详细介绍了一种高效的数据结构——树状数组,并通过具体示例讲解了如何使用树状数组进行更新和查询操作,特别适用于解决区间加减及求和问题。

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

//http://acm.hdu.edu.cn/showproblem.php?pid=1166

大意:给你一串数,然后会根据题意选择一点增加或减少,或者询问某区间的人数有多少?之前用线段树写了,而这题可以用树状树状来做,更加方便更加快速。

说下树状数组的三个主要函数:


#include<iostream>
using namespace std;
#define lowbit(x) (x)&(-x)  
int N;  
int c[50005];
//更新整个树状数组  
void update(int pos, int value)  
{  
    while (pos <= N)   
    {  
        c[pos] += value;  
        pos += lowbit(pos);  
    }  
} 
//查询前pos项和  
int query(int pos)   
{  
    int sum = 0;  
    while (pos > 0)   
    {  
        sum += c[pos];  
        pos -= lowbit(pos);  
    }  
    return sum;  
}  
int main()  
{  
    int cas;  
    int t = 1;  
    scanf("%d", &cas);  
    while (cas--)   
    {  
        printf("Case %d:\n", t++);  
        int temp;  
        scanf("%d", &N);  
        memset(c, 0, sizeof(c));  
        for (int i = 1; i <= N; i++)   
        {  
            scanf("%d", &temp);  
            update(i, temp);  
        }  
        char str[10];  
        while (scanf("%s", str) != EOF)   
        {  
            if (str[0] == 'E')  
            break;
            int a, b;  
            scanf("%d%d", &a, &b);  
            if (str[0] == 'A') 
			{  
                update(a, b);  
            } 
			else if (str[0] == 'S') 
			{  
                update(a, -b);  
            } 
			else 
			{  
                printf("%d\n", query(b) - query(a - 1));  
            }  
        }  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值