Kimi has a lot of candies, and divides them into piles, where the ith pile contains Ai candies. Each time Kimi will choose an interval [l,r], and calculate the total amount of Al,Al+1,…,Ar. It‘s a hard task, and you‘re required to solve it.
标签:
Kimi has a lot of candies, and divides them into piles, where the ith pile contains Ai candies. Each time Kimi will choose an interval [l,r], and calculate the total amount of Al,Al+1,…,Ar. It‘s a hard task, and you‘re required to solve it.
An integer T(T≤10) will exist in the first line of input, indicating the number of test cases. Each test case begins with the number of pilesN(1≤N≤105). The second line contains N integers Ai(1≤Ai≤100), where Ai stands for the number of candies in the ith pile. The next line is the number of queries M(1≤M≤105). The next M lines, each with two integers l,r(1≤l≤r≤N), describe the queried intervals.
For each test case, output the total amount of candies in the queried interval.
1 #include<cstdio> 2 #include<cstring> 3 const int MAXN = 1000008; 4 int a[MAXN]; 5 int m; 6 int lowbit(int r){ 7 return r & (-r); 8 } 9 int sum(int x){ 10 int ret = 0; 11 while(x > 0){ 12 ret += a[x]; 13 x -= lowbit(x); 14 } 15 return ret; 16 } 17 void add(int i,int x){ 18 while(i <= m){ 19 a[i] += x; 20 i += lowbit(i); 21 } 22 } 23 int main(){ 24 int n; 25 scanf("%d",&n); 26 while(n--){ 27 memset(a,0,sizeof(a)); 28 scanf("%d",&m); 29 int i,j; 30 for(i = 1;i <= m;i++){ 31 int x; 32 scanf("%d",&x); 33 add(i,x); 34 } 35 int t; 36 scanf("%d",&t); 37 while(t--){ 38 int num1,num2; 39 scanf("%d%d",&num1,&num2); 40 printf("%d\n",sum(num2) - sum(num1 - 1)); 41 } 42 } 43 }
相似的简单题链接:士兵杀敌(一) 只涉及查询区间和
南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的。
小工是南将军手下的军师,南将军经常想知道第m号到第n号士兵的总杀敌数,请你帮助小工来回答南将军吧。
南将军的某次询问之后士兵i可能又杀敌q人,之后南将军再询问的时候,需要考虑到新增的杀敌数
5 6 1 2 3 4 5 QUERY 1 3 ADD 1 2 QUERY 1 3 ADD 2 3 QUERY 1 2 QUERY 1 5
6 8 8 20
1 2 #include<stdio.h> 3 #define size 1000008 4 5 int a[size]; 6 int N; 7 int lowbit(int r) 8 { 9 return r & (-r); 10 } 11 int sum(int x) 12 { 13 int ret = 0; 14 while(x>0) 15 { 16 ret+=a[x];x-=lowbit(x); 17 } 18 return ret; 19 } 20 void add(int i,int x) 21 { 22 while(i<=N) 23 { 24 a[i]+=x; 25 i+=lowbit(i); 26 } 27 } 28 29 int main() 30 { 31 int M,m,n,x; 32 scanf("%d%d",&N,&M); 33 for(int i=1;i<=N;i++) 34 { 35 scanf("%d",&x); 36 add(i,x); 37 } 38 while(M--) 39 { 40 char ac[5]; 41 scanf("%s%d%d",ac,&m,&n); 42 if(ac[0]==‘Q‘) 43 { 44 printf("%d\n",sum(n)-sum(m-1)); 45 } 46 else 47 { 48 add(m,n); 49 } 50 } 51 return 0; 52 }
【树状数组(二叉索引树)】轻院热身—candy、NYOJ-116士兵杀敌(二)
标签:
原文地址:http://www.cnblogs.com/zhengbin/p/4462942.html