0131
今天学习的是:树状数组
https://www.luogu.com.cn/problem/P3374
1 #include<iostream> 2 using namespace std; 3 int n,m,c[500001],a[5000001]; 4 int lowbit(int i) 5 { 6 return i&(-i); 7 } 8 void cc(int i,int data) 9 { 10 while(i<=n) c[i]+=data,i+=lowbit(i); 11 } 12 int sum1(int k) 13 { 14 int s=0; 15 while(k>0) s+=c[k],k-=lowbit(k); 16 return s; 17 } 18 int main() 19 { 20 int x1,x2; 21 cin>>n>>m; 22 for(int i=1;i<=n;i++) 23 { 24 cin>>a[i]; 25 cc(i,a[i]); 26 } 27 while(m--) 28 { 29 int o; 30 cin>>o>>x1>>x2; 31 if(o==1) cc(x1,x2); 32 else cout<<sum1(x2)-sum1(x1-1)<<endl; 33 } 34 return 0; 35 }
https://www.luogu.com.cn/problem/P3368
1 #include<iostream> 2 using namespace std; 3 int n,m,a[500001]; 4 long long c[500001]; 5 int lowbit(int x) 6 { 7 return x&(-x); 8 } 9 void cc(int x,int k) 10 { 11 while(x<=n) 12 { 13 c[x]+=k; 14 x+=lowbit(x); 15 } 16 return; 17 } 18 long long sum(int x) 19 { 20 long long res=0; 21 while(x) 22 { 23 res+=c[x]; 24 x-=lowbit(x); 25 } 26 return res; 27 } 28 int main() 29 { 30 cin>>n>>m; 31 for(int i=1;i<=n;i++) 32 { 33 cin>>a[i]; 34 cc(i,a[i]-a[i-1]); 35 } 36 while(m--) 37 { 38 int op;cin>>op; 39 if(op==1) 40 { 41 int l,r,k; 42 cin>>l>>r>>k; 43 cc(l,k),cc(r+1,-k); 44 } 45 else 46 { 47 int x; 48 cin>>x; 49 cout<<sum(x)<<endl; 50 } 51 } 52 return 0; 53 }

浙公网安备 33010602011771号