士兵杀敌(二)

//本题主要运用了树组数组的知识,学了后就会做了

#include<stdio.h> #include<string.h> const int N=1000010; int n,c[N]; //该函数功能是求出n二进制中最右边0的个数的2次幂,也等于c[n]包含的元素个数num[n-lowbit(n)+1]+...+num[n] int lowbit(int n) { return n&(-n);     //return (n&(n^(n-1)); //^(Xor):异或关系
} //更新数组中pos的值使它加上inc,更新首先更新c[pos]一直更新该点的父节点到顶端 void add(int pos,int x) { while(pos<=n) { c[pos]+=x; pos+=lowbit(pos); } } //该函数功能是求的前n项元素的和 int getSum(int n) { int s=0; while(n>0) { s+=c[n]; n-=lowbit(n); } return s; } int main() { freopen("in2.txt","r",stdin); int m,i,x; scanf("%d%d",&n,&m); for(i=1;i<=n;i++) { scanf("%d",&x); add(i,x); } int a,b; char str[6]; while(m--) { getchar(); scanf("%s%d%d",str,&a,&b); if(str[0]=='Q') printf("%d\n",getSum(b)-getSum(a-1)); else add(a,b); } return 0; }

  

原文地址:https://www.cnblogs.com/yaling/p/2837950.html