标签:ges line 技术 set include 分享 for nbsp div
推理过程
维护两个数组,d[i] = a[i] - a[i - 1],f[i] = i * d[i],剩下的,区间更新和区间查询就和【一维树状数组区间更新单点查询】一样了。
实现源代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n = 20;
int a[40], d[40], f[40];
int query(int* arr, int x) {
int res = 0;
for(int i = x; i > 0; i -= (i & -i))res += arr[i];
return res;
}
void update(int* arr, int x, int val) {
for(int i = x; i <= n; i += (i & -i))arr[i] += val;
}
inline int getsum(int x){
return (x + 1) * query(d, x) - query(f, x);
}
int main() {
memset(a, 0, sizeof(a));
memset(d, 0, sizeof(d));
memset(f, 0, sizeof(f));
for(int i = 1; i <= n; ++i) {
a[i] = i;
int t = a[i] - a[i - 1];
update(d, i, t);
update(f, i, t * i);
}
for(int i = 1; i <= n; ++i) {
printf("sum(%d) = %d\n", i, getsum(i));
}
puts("------------------------------------------");
int x = 1, y = 10, val = 20;
update(d, x, val);
update(d, y + 1, -val);
update(f, x, val * x);
update(f, y + 1, -val * (y + 1));
printf("sum(10) = %d\n", getsum(10));
return 0;
}
标签:ges line 技术 set include 分享 for nbsp div
原文地址:http://www.cnblogs.com/565261641-fzh/p/7648071.html