HDU 1166 - 敌兵布阵

题目大意:中文题

解题思路:因为数据量比较大, 普通暴力算法肯定会超时,采用线段树或者树状数组,这里用树状数组解答。树状数组的基本入门我是看了这个博客的还算挺清楚的,一个地方可能是我理解偏差,lowbit(x)计算的2*k代表的应该是,二进制下从最低位往最高位找出现的第一个1代表的数的大小。看过以后就很清晰了

ac代码:

#include <iostream>
#include <cstring>
using namespace std;
int t, a[50005], c[50005], n, temp1, temp2, cnt=1;
char com[15];
int lowbit(int x)
{
    return x&(-x);
} 
int getsum(int x)
{
    int ans=0;
    for (int i=x; i>0; i-=lowbit(i))
        ans += c[i];
    return ans;
}
void add(int x, int y)
{
    for (int i = x; i <= n; i+=lowbit(i))
        c[i] += y;
}
int main()
{
	scanf("%d", &t);
	while (t--){
		scanf("%d", &n);
		c[0] = 0;
		for (int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        for (int i = 1; i <= n; i++){
            c[i] = 0;
            temp1 = lowbit(i);
            for (int j = i-temp1+1; j <= i; j++)
                c[i] += a[j];
        }
        printf("Case %d:\n", cnt++);
        while (1){
            scanf("%s", com);
            if (!strcmp(com, "End"))
            	break;
            scanf("%d%d", &temp1, &temp2);
            if (!strcmp(com, "Query"))
                printf("%d\n", getsum(temp2)-getsum(temp1-1));
            else if (!strcmp(com, "Add"))
                add(temp1, temp2);
            else if (!strcmp(com, "Sub"))
                add(temp1, -temp2);
        }
	}
return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值