https://www.luogu.org/problemnew/show/P3374
单点修改, 区间查询
1 //2018年2月18日17:58:16 2 #include <iostream> 3 #include <cstdio> 4 using namespace std; 5 6 const int N = 500001; 7 int n, m; 8 int a[N], c[N]; 9 10 inline int lowbit(int x){ 11 return x & (-x); 12 } 13 void add(int x, int k){ 14 for(int i=x;i<=n;i+=lowbit(i)) c[i] += k; 15 } 16 17 int sum(int x){ 18 int res = 0; 19 for(int i=x; i; i-=lowbit(i)) res += c[i]; 20 return res; 21 } 22 23 int main(){ 24 scanf("%d%d", &n, &m); 25 for(int i=1;i<=n;i++){ 26 scanf("%d", &a[i]); 27 add(i, a[i]); 28 } 29 for(int i=1;i<=m;i++){ 30 int opt, x, k; 31 scanf("%d%d%d", &opt, &x, &k); 32 if(opt == 1){ 33 add(x, k); 34 }else if(opt == 2){ 35 printf("%d\n", sum(k)-sum(x-1)); 36 } 37 } 38 39 40 return 0; 41 }
https://www.luogu.org/problemnew/show/P3368
区间修改, 单点查询
1 //2018年2月18日21:10:31 2 #include <iostream> 3 #include <cstdio> 4 using namespace std; 5 6 const int N = 500001; 7 int n, m; 8 int c[N], last; 9 int opt, x, y, k; 10 11 inline int lowbit(int x){ 12 return x & (-x); 13 } 14 15 void add(int x, int k){ 16 for(int i=x; i<=n; i+=lowbit(i)) c[i] += k; 17 } 18 19 int sum(int x){ 20 int res = 0; 21 for(int i=x; i; i-=lowbit(i)) res += c[i]; 22 return res; 23 } 24 25 int main(){ 26 scanf("%d%d", &n, &m); 27 for(int i=1;i<=n;i++){ 28 scanf("%d", &x); 29 add(i, x-last); 30 last = x; 31 } 32 for(int i=1;i<=m;i++){ 33 scanf("%d", &opt); 34 if(opt == 1){ 35 scanf("%d%d%d", &x, &y, &k); 36 add(x, k); 37 add(y+1, -k); 38 }else if(opt == 2){ 39 scanf("%d", &x); 40 printf("%d\n", sum(x)); 41 } 42 } 43 44 return 0; 45 }
原文地址:https://www.cnblogs.com/sineagle/p/8453222.html
时间: 2024-10-11 01:58:59