P3368 [template] Fenwick tree 2

Links: P3368 [template] Fenwick tree 2

--------------------------------------------

A look at the template? Please click

--------------------------------------------

 

Well, this question let us achieve a single point of query and modify the interval. But according to: 1 , we can see that the operation Fenwick tree only modify a single point and interval sum, then how to achieve?

We can not be forced to add these features, you need to be transformed. The easiest way is to change the array.

--------------------------------------------

There is an array, we just change two of the points, you can achieve change intervals. As long as we add a short interval, you can find a point and. This array is - difference.

Yes, when we realize Fenwick tree, we recorded the array than its value, but the difference! ! !

The rest of it is all the same.

I do not know the prefix and / differential? Look at the big brother

--------------------------------------------

 

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int t[500001];
 5 int n,m;
 6 int now;
 7 int f,x,y;
 8 int last;
 9 int v;
10 int lowbit(int x){
11     return x &-x;
12 }
13 void add(int p,int x){
14     while(p<=n){
15         t[p]+=x;
16         p+=lowbit(p);
17     }
18 }
19 int sum(int n){
20     int ans=0;
21     while(n){
22         ans+=t[n];
23         n-=lowbit(n);
24     }
25     return ans;
26 }
27 int main(){
28     scanf("%d%d",&n,&m);
29     for(int i=1;i<=n;++i){
30         scanf("%d",&now);
31         add(i,now-last);
32         last=now;
33     }
34     for(int i=1;i<=m;++i){
35         cin>>f;
36         {
37             if(f==1)
38             {
39             //    scanf("%d",&v);
40             cin>>x>>y>>v;
41                 add(x,v);
42                 add(y+1,-v);
43             }
44             if(f==2){
45                 cin>>x;
46             cout<<sum(x)<<endl;
47             
48             
49             }
50         }
51     }
52     return 0;
53 }
Ac

 

Guess you like

Origin www.cnblogs.com/For-Miku/p/11246230.html