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

来源:互联网 发布:2016安全知识 网络竞赛 编辑:程序博客网 时间:2024/05/14 14:41

//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));              }          }      }  }  


1 0
原创粉丝点击