Title Description
Given a length of n (n <= 100000), the initial values are 0 as a sequence of numbers on the modified x (x <= 10000) certain locations times, each time adding a number, and submit y (y <= 10000) issue, and seek each segment interval. One second time limit.
Input and output formats
Input formats:
The first line number 1, n denotes the length of the sequence
Second line number 1, w denotes the number of operations
W is sequentially behind the line, respectively and added interrogate operation
Thereto, denoted by x, y represented by the interrogation
X is the format "xa b" represents a plus b at a position of the sequence
y is in the format of "ya b" indicates a query and adding the interval b
Output formats:
One per line number, which are the result of each inquiry
Sample input and output
5 4 x 8 March y 1 3 x April 9 and April 3
8 17
segments Number practices:
// luogu-judger-enable-o2 #include<cstdio> #include<iostream> #include<cstring> #include<cstdlib> #include<algorithm> #include<cmath> #define maxn 100007 using namespace std; int n,m,x,y,z; char jjj[4]; long long Sum[maxn<<2],Add[maxn<<2]; int A[maxn]; void PushUp(int rt){Sum[rt]=Sum[rt*2]+Sum[rt*2+1];} void Build(int l,int r,int rt){ if(l==r) { Sum[rt]=A[l]; return; } int m=(l+r)>>1; Build(l,m,rt<<1); Build(m+1,r,rt<<1|1); PushUp(rt); } void PushDown(int rt,int ln,int rn){ if(Add[rt]){ Add[rt<<1]+=Add[rt]; Add[rt<<1|1]+=Add[rt]; Sum[rt<<1]+=Add[rt]*ln; Sum[rt<<1|1]+=Add[rt]*rn; Add[rt]=0; } } long long Query(int L,int R,int l,int r,int rt){ if(L <= l && r <= R) return Sum[rt]; int m=(l+r)>>1; PushDown(rt,m-l+1,r-m); long long ANS=0; if(L <= m) ANS+=Query(L,R,l,m,rt<<1); if(R > m) ANS+=Query(L,R,m+1,r,rt<<1|1); return ANS; } void Update(int L,int R,int C,int l,int r,int rt){ if(L <= l && r <= R){ Sum[rt]+=C*(r-l+1); Add[rt]+=C; return ; } int m=(l+r)>>1; PushDown(rt,m-l+1,r-m); if(L <= m) Update(L,R,C,l,m,rt<<1); if(R > m) Update(L,R,C,m+1,r,rt<<1|1); PushUp(rt); } int main(){ while(scanf("%d%d",&n,&m)!=EOF){ for(int i=1;i<=n;i++) A[i]=0; Build(1,n,1); while(m--) { scanf("%s",jjj); if(jjj[0]=='x') { scanf("%d%d",&x,&z); Update(x,x,z,1,n,1); } else { scanf("%d%d",&x,&y); printf("%lld\n",Query(x,y,1,n,1)); } } } return 0; }
Fenwick tree solution as follows:
’
#include<iostream> using namespace std; const int MAXN=100000+2; int a[MAXN]; int n,w; int lowbit(int x){ return x&(-x); } void add(int p,int x){ while(p<=n){ a[p]+=x; p+=lowbit(p); } } int ask(int p){ int ans=0; while(p>0){ ans+=a[p]; p-=lowbit(p); } return ans; } int main(){ cin>>n>>w; for(int i=1;i<=w;i++){ char q; int y,z; cin>>q>>y>>z; if(q=='x') add(y,z); else cout<<ask(z)-ask(y-1)<<endl; } return 0; }