CodeForces 315B(线段树+区间更新)
问题描述:
Sereja has got an array, consisting of n integers, a1, a2, …, an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
- Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
- Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).
- Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains nspace-separated integers a1, a2, …, an (1 ≤ ai ≤ 109) — the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Example
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
问题分析:线段树的区间更新!
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=1e5+100;
struct note
{
int l,r,val;
}tree[maxn*4];
int a[maxn];
void build(int root,int ll,int rr)
{
tree[root].l=ll;
tree[root].r=rr;
tree[root].val=0;
if (ll==rr) {
tree[root].val=a[ll];
return ;
}
int mid=(tree[root].l+tree[root].r)>>1;
build(root<<1,ll,mid);
build(root<<1|1,mid+1,rr);
}
void pushdown(int root)
{
if (tree[root].val) {
tree[root<<1].val+=tree[root].val;
tree[root<<1|1].val+=tree[root].val;
tree[root].val=0;
}
}
void update(int root,int l,int r,int cur,int p)
{
int ll=tree[root].l;
int rr=tree[root].r;
if (l<=ll&&r>=rr) {
if (p==2) tree[root].val+=cur;
else tree[root].val=cur;
return ;
}
pushdown(root);
int mid=(ll+rr)>>1;
if (l<=mid) update(root<<1,l,r,cur,p);
if (r>mid) update(root<<1|1,l,r,cur,p);
}
int query(int root,int pos)
{
int l=tree[root].l;
int r=tree[root].r;
if (l==r) {
return tree[root].val;
}
pushdown(root);
int mid=(l+r)>>1;
if (pos<=mid)
return query(root<<1,pos);
else
return query(root<<1|1,pos);
}
int main()
{
int n,m;
while (scanf("%d%d",&n,&m)!=EOF) {
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
for (int i=1;i<=m;i++) {
int t;
scanf("%d",&t);
if (t==1) {
int pos,x;
scanf("%d%d",&pos,&x);
update(1,pos,pos,x,1);
}
else if (t==2) {
int v;
scanf("%d",&v);
update(1,1,n,v,2);
}
else if (t==3) {
int pos;
scanf("%d",&pos);
printf("%d\n",query(1,pos));
}
}
}
return 0;
}
还没有评论,来说两句吧...