树状数组 -- hdu敌兵布阵 -- 树状数组

2017年5月7日

题目来源:
http://acm.hdu.edu.cn/showproblem.php?pid=1166

分析:
每次只修改一个点,求的是一个区间的内容

代码如下:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
const int maxn = 99999;

int c[maxn],a[maxn];
int n;
int x1,x2;

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

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

int sum(int x)
{
      int s = 0;

      while(x > 0)
      {
            s += c[x];
            x -= lowbit(x);
      }
      return s;
}

int Getsum(int i , int j )
{
      return sum(j) - sum(i-1);
}

int main()
{
    int T;
    cin >> T;
    for(int i = 1; i <= T; i++)
    {
        memset(a,0,sizeof(a));
        memset(c,0,sizeof(c));

        cout << "Case "<<i <<":"<< endl;

        cin >> n;

        for(int j = 1; j <= n ; j++)
        {
              cin >> a[j];
              update(j,a[j]);
        }

        string oper;

        while(cin >> oper)
        {
              if(oper == "End")
                  break;
              cin >>  x1 >> x2;
              if(oper == "Query")
              {
                    cout << Getsum(x1,x2) << endl;
              }
              if(oper == "Add")
              {
                    a[x1] += x2;
                    update(x1,x2);
              }
              if(oper == "Sub")
              {
                    a[x1] -= x2;
                    update(x1,-x2);
              }
        }


    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值