南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的。
小工是南将军手下的军师,南将军现在想知道第m号到第n号士兵的总杀敌数,请你帮助小工来回答南将军吧。
注意,南将军可能会问很多次问题。
5 2 1 2 3 4 5 1 3 2 4
6 9
题解:树状数组:
代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<algorithm> 5 using namespace std; 6 #define MAX(x,y)(x>y?x:y) 7 #define MIN(x,y)(x<y?x:y) 8 //#define LOCAL 9 const int INF=0x3f3f3f3f; 10 const int MAXN=1000010; 11 int tree[MAXN]; 12 int N; 13 int lowbit(int x){ 14 return x&(-x); 15 } 16 void update(int x,int y){ 17 while(x<=N){ 18 tree[x]+=y; 19 x+=lowbit(x); 20 } 21 } 22 int query(int x){ 23 int ans=0; 24 while(x){ 25 ans+=tree[x]; 26 x-=lowbit(x); 27 } 28 return ans; 29 } 30 int main(){ 31 #ifdef LOCAL 32 freopen(data.in,"r",stdin); 33 freopen(data.out,"w",stdout); 34 #endif 35 int M; 36 scanf("%d%d",&N,&M); 37 int a,b; 38 for(int i=1;i<=N;i++){ 39 scanf("%d",&a); 40 update(i,a); 41 } 42 while(M--){ 43 scanf("%d%d",&a,&b); 44 printf("%d\n",query(b)-query(a-1)); 45 } 46 return 0; 47 }
原文:http://www.cnblogs.com/handsomecui/p/4893011.html