1.HDU 1166  http://acm.hdu.edu.cn/showproblem.php?pid=1166

题目大意:
了解地方的兵营人数,每次询问告知区间内的总人数,其中会有兵营人数变更的更新操作

这里要用到求和的query:

int query(int x,int y)
{

    int
i=D+x-1,j=D+y+1,ans=0;
    for
(;i^j^1;i>>=1,j>>=1){
        if
(~i&1) ans+=tree[i^1];
        if
(j&1) ans+=tree[j^1];
    }

    return
ans;
}

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <string>
 5 using namespace std;
 6 
 7 #define N 50005
 8 
 9 int a[N],tree[200010];
10 int D;
11 string s;
12 
13 void update(int x)
14 {
15     for(int i=x;i^1;i>>=1){
16         tree[i>>1]=tree[i]+tree[i^1];
17     }
18 }
19 
20 int query(int x,int y)
21 {
22     int i=D+x-1,j=D+y+1,ans=0;
23     for(;i^j^1;i>>=1,j>>=1){
24         if(~i&1) ans+=tree[i^1];
25         if(j&1) ans+=tree[j^1];
26     }
27     return ans;
28 }
29 int main()
30 {
31     int T,n,c,d;
32     cin>>T;
33     for(int i=1;i<=T;i++){
34         D=1;
35         memset(tree,0,sizeof(tree));
36         scanf("%d",&n);
37         for(int j=1;j<=n;j++) scanf("%d",&a[j]);
38         while(D<n+2) D<<=1;
39         for(int j=1;j<=n;j++) tree[D+j]=a[j];
40         for(int j=D-1;j>=1;j--) tree[j]=tree[j<<1]+tree[j<<1|1];
41         printf("Case %d:\n",i);
42         while(cin>>s){
43             if(s=="End") break;
44 
45             else if(s=="Add"){
46                 scanf("%d%d",&c,&d);
47                 tree[D+c]+=d;
48                 update(D+c);
49             }
50             else if(s=="Sub"){
51                 scanf("%d%d",&c,&d);
52                 tree[D+c]-=d;
53                 update(D+c);
54             }
55             else if(s=="Query"){
56                 scanf("%d%d",&c,&d);
57                 printf("%d\n",query(c,d));
58             }
59         }
60     }
61     return 0;
62 }
View Code

相关文章:

  • 2021-12-21
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
猜你喜欢
  • 2021-08-25
  • 2022-02-13
  • 2021-07-31
  • 2021-06-03
  • 2021-07-05
  • 2021-08-13
  • 2021-11-17
相关资源
相似解决方案