2 条题解
-
1zengzhiyu LV 6 MOD @ 2024-01-29 14:29:30
树状数组代码
#include<stdio.h> #include<string.h> #include<math.h> int a[50005]; int n; int lowbit(int t) { return t&(-t); } void insert(int t,int d) { while(t<=n) { a[t]+=d; t+=lowbit(t); } } int getsum(int t) { int sum=0; while(t>0) { sum+=a[t]; t-=lowbit(t); } return sum; } int main() { int T,i,j,k,t; scanf("%d",&T); t=0; while(T--) { memset(a,0,sizeof(a)); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&k); insert(i,k); } char str[10]; scanf("%s",str); while(str[0]!='E') { int x,y; scanf("%d%d",&x,&y); if(str[0]=='Q') printf("%d\n",getsum(y)-getsum(x-1)); else if(str[0]=='A') insert(x,y); else if(str[0]=='S') insert(x,(-1)*y); scanf("%s",str); } } return 0; }
-
02024-01-29 14:29:58@
线段树代码
#include<iostream> #define int long long using namespace std; const int maxn = 1e5+5; int n,q,op,x,y,k; int a[maxn]; struct node { int l,r; int sum,lazy; void update(int val) { sum+=(r-l+1)*val; lazy+=val; } }tree[maxn<<2]; inline void pushDown(int id) { int lazyval=tree[id].lazy; if(lazyval) { tree[id<<1].update(lazyval); tree[id<<1|1].update(lazyval); tree[id].lazy=0; } } inline void pushUp(int id) { tree[id].sum=tree[id<<1].sum+tree[id<<1|1].sum; } void build(int id,int l,int r) { tree[id].l=l;tree[id].r=r; tree[id].sum=0; tree[id].lazy=0; if(l==r) { tree[id].sum=a[l]; } else { int mid=l+((r-l)>>1); build(id<<1,l,mid); build(id<<1|1,mid+1,r); pushUp(id); } } void update(int id, int l, int r,int val) { if(l<=tree[id].l&&tree[id].r<=r) { tree[id].update(val); } else { pushDown(id); int mid = (tree[id].l + tree[id].r) >> 1; if(mid >= l) update(id<<1, l, r, val); if(r > mid) update(id<<1|1, l, r, val); pushUp(id); } } int query(int id, int l, int r) { if(l <= tree[id].l && tree[id].r <= r) { return tree[id].sum; } else { pushDown(id); int ans = 0; int mid = (tree[id].l + tree[id].r) >> 1; if(mid >= l) ans += query(id<<1, l, r); if(r > mid) ans += query(id<<1|1, l, r); pushUp(id); return ans; } } signed main() { int t; cin>>t; while(t--) { cin>>n; for(int i=1;i<=n;i++) { cin>>a[i]; } build(1,1,n); string s; while(1) { cin>>s; if(s=="Add") { cin>>x>>k; update(1,x,x,k); } else if(s=="Sub") { cin>>x>>k; update(1,x,x,-k); } else if(s=="Query") { cin>>x>>y; cout<<query(1, x, y)<<"\n"; } else { break; } } } return 0; }
- 1