题目描述 Description
给你N个数,有两种操作
1:给区间[a,b]的所有数都增加X
2:询问第i个数是什么?
输入描述 Input Description
第一行一个正整数n,接下来n行n个整数,再接下来一个正整数Q,表示操作的个数. 接下来Q行每行若干个整数。如果第一个数是1,后接3个正整数a,b,X,表示在区间[a,b]内每个数增加X,如果是2,后面跟1个整数i, 表示询问第i个位置的数是多少。
输出描述 Output Description
对于每个询问输出一行一个答案
样例输入 Sample Input
3
1
2
3
2
1 2 3 2
2 3
样例输出 Sample Output
5
数据范围及提示 Data Size & Hint
数据范围
1<=n<=100000
1<=q<=100000
分析:
这题是线段树区间修改的模板题,可以用懒标记去做。
但是这题可以不用懒标记去做。我们可以用线段树的叶子节点记录每个点的真实值。然后非叶子节点记录的是这个区间增加的值,我们要求这个点的值的话,直接从根节点搜到叶子节点求和就行了。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=100000+5; inline int read() { int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();} return x*f; } int n,m,len; int a[maxn]; struct node { int l,r,lc,rc,c; }tr[maxn<<1]; inline void bt(int x,int y) { len++; int now=len; tr[now].l=x;tr[now].r=y;tr[now].c=0; if(x==y) tr[now].c=a[x]; else { int mid=(x+y)>>1; tr[now].lc=len+1; bt(x,mid); tr[now].rc=len+1; bt(mid+1,y); } } inline void update(int now,int x,int y,int k) { if(tr[now].l==x&&tr[now].r==y) tr[now].c+=k; else { int lc=tr[now].lc,rc=tr[now].rc; int mid=(tr[now].l+tr[now].r)>>1; if(y<=mid) update(lc,x,y,k); else if(x>=mid+1) update(rc,x,y,k); else {update(lc,x,mid,k); update(rc,mid+1,y,k);} } } inline int query(int now,int x) { if(tr[now].l==tr[now].r) return tr[now].c; else { int lc=tr[now].lc,rc=tr[now].rc; int mid=(tr[now].l+tr[now].r)>>1; if(x<=mid) return tr[now].c+query(lc,x); else return tr[now].c+query(rc,x); } } int main() { n=read(); for(int i=1;i<=n;i++) a[i]=read(); bt(1,n); m=read(); for(int i=1;i<=m;i++) { int p,x,y,k; p=read(); if(p==1) { x=read();y=read();k=read(); update(1,x,y,k); }else if(p==2) { x=read(); printf("%d ",query(1,x)); } } return 0; }