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

来源:互联网 发布:深圳gdp首超广州 知乎 编辑:程序博客网 时间:2024/06/08 03:19

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;}
0 0
原创粉丝点击