树状数组(区间修改,区间查询 )

 1 #include
 2 #include 
 3 using namespace std;
 4 
 5 long long n,m;
 6 long long a[500009]; 
 7 long long c[500009],d[500009];
 8 long long lowbit(long long x)
 9 {
10     return (x&(-x));
11 }
12 void change(long long *e,long long x,long long k)
13 {
14     for(int i=x;i<=n;i+=lowbit(i))
15     {
16         e[i]+=k;
17     }
18 }
19 long long query(long long *e,long long x)
20 {
21     long long sum=0;
22     for(int i=x;i>=1;i-=lowbit(i))
23     {
24         sum+=e[i];
25     }
26     return sum;
27 }
28 int main()
29 {
30     cin>>n>>m;
31     for(int i=1;i<=n;i++)
32     {
33         cin>>a[i];
34         change(c,i,a[i]-a[i-1]);
35         change(d,i,(long long)(i-1)*(a[i]-a[i-1]));
36     }
37     for(int i=1;i<=n;i++)
38     {
39         cout<" ";
40     }
41     cout<<endl;
42     for(int i=1;i<=n;i++)
43     {
44         cout<" ";
45     }
46     for(int i=1;i<=m;i++)
47     {
48         long long p;
49         cin>>p;
50         if(p==1)//修改 
51         {
52             long long r,l,v;
53             cin>>r>>l>>v;
54             change(c,r,v);
55             change(c,l+1,-v);
56             change(d,r,(long long)(r-1)*v);
57             change(d,l+1,(long long)-l*v);
58         }
59         if(p==2)//统计 
60         {
61             long long r,l;
62             cin>>r>>l;
63             long long t1=query(c,r-1)*(r-1)-query(d,r-1);
64             long long t2=query(c,l)*l-query(d,l);
65             printf("%lld\n",t2-t1);
66         }
67     }
68     return 0;
69 }
70 /*
71 5 2
72 1 7 6 5 8
73 1 2 3 1//修改【2~3】+1 
74 2 2 4//查询2~4 
75 */

 

你可能感兴趣的:(树状数组(区间修改,区间查询 ))