lowbit操作:
int lowbit(int x){
return x & (-x);
}
更新操作:
void update(int x, int num){
for(int i = x; i <= N; i += lowbit(i)){
tree[i] += num;
}
}
求和操作:
int getSum(int x){
int res = 0;
for(int i = x; i > 0; i -= lowbit(i)){
res += tree[i];
}
return res;
}
单点更新,区间查询
https://cn.vjudge.net/problem/HDU-1166
#include<bits/stdc++.h>
using namespace std;
const int maxn = 50000+5;
int d[maxn];
int t,n;
string c;
int lowbit(int x){
return x & (-x);
}
void update(int x, int num){
for(int i = x; i <= n; i += lowbit(i)){
d[i] += num;
}
}
int getSum(int x){
int res = 0;
for(int i = x; i > 0; i -= lowbit(i)){
res += d[i];
}
return res;
}
int main(){
int a,x,y;
cin>>t;
for(int i=1;i<=t;i++){
cin>>n;
printf("Case %d:\n",i);
memset(d,0,sizeof d);
for(int l=1;l<=n;l++){
cin>>a;
update(l,a);
}
while(cin>>c){
if(c=="Query"){
cin>>x>>y;
cout<<getSum(y)-getSum(x-1)<<endl;//单点求和,差分树状数组里面的值不是差分数组的值
}else if(c=="Add"){
cin>>x>>y;
update(x,y);//单点更新,树状数组存前缀和
}else if(c=="Sub"){
cin>>x>>y;
update(x,-y);
}else{
break;
}
}
}
return 0;
}
区间更新,单点查询
https://www.luogu.org/problemnew/show/P3368
#include<bits/stdc++.h>
using namespace std;
const int maxn = 500000+5;
int a[maxn],d[maxn];
int n,m;
int lowbit(int x){
return x & (-x);
}
void update(int x, int num){
for(int i = x; i <= n; i += lowbit(i)){
d[i] += num;
}
}
int getSum(int x){
int res = 0;
for(int i = x; i > 0; i -= lowbit(i)){
res += d[i];
}
return res;
}
int main(){
int A,B,C,D;
cin>>n>>m;
a[0]=0;
for(int i=1;i<=n;i++){
cin>>a[i];
update(i,a[i]-a[i-1]);//区间更新,树状数组存差分
}
for(int i=0;i<m;i++){
cin>>A;
if(A==1){
cin>>B>>C>>D;
update(B,D);
update(C+1,-D);
}
if(A==2){
cin>>B;
cout<<getSum(B)<<endl;
}
}
return 0;
}
区间更新,区间查询
https://cn.vjudge.net/problem/POJ-3468
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 7;
LL tree1[maxn], tree2[maxn], a[maxn];
int n, m;
int lowbit(int x){
return x & (-x);
}
void update(int i, LL x){
for(int j = i; j <= n; j += lowbit(j)){
tree1[j] += x;
tree2[j] += x * (i-1);
}
}
LL getSum(int i){
LL res = 0;
for(int j = i; j >= 1; j -= lowbit(j)){
res += i * tree1[j] - tree2[j];
}
return res;
}
int main()
{
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
scanf("%lld", &a[i]);
update(i, a[i] - a[i-1]);
}
char c;
int x, y, k;
while(m--){
scanf(" %c", &c);
if(c == 'C'){
scanf("%d %d %d", &x, &y, &k);
update(x, k);
update(y+1, -k);
}
else {
scanf("%d %d", &x, &y);
printf("%lld\n", getSum(y) - getSum(x-1));
}
}
return 0;
}
2369

被折叠的 条评论
为什么被折叠?



