codevs 1081 线段树练习2 (线段树)

题目:

题目描述 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 <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm> using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int maxn=1e5+;
int n,m,x,y,v,res,ans,op;
int a[maxn]; struct node{
int l,r,w,mark;
}tree[maxn<<]; void build(int l,int r,int rt){
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].w=a[l];
return;
}
int mid=(l+r)/;
build(l,mid,rt*);
build(mid+,r,rt*+);
tree[rt].w=tree[rt*].w+tree[rt*+].w;
} void pushdown(int rt){
tree[rt*].mark+=tree[rt].mark;
tree[rt*+].mark+=tree[rt].mark;
tree[rt*].w+=tree[rt].mark*(tree[rt*].r-tree[rt*].l+);
tree[rt*+].w+=tree[rt].mark*(tree[rt*+].r-tree[rt*+].l+);
tree[rt].mark=;
} void update(int rt){
if(tree[rt].l>=x && tree[rt].r<=y){
tree[rt].w+=v*(tree[rt].r-tree[rt].l+);
tree[rt].mark+=v;
return;
}
if(tree[rt].mark) pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/;
if(x<=mid) update(rt*);
if(y>mid) update(rt*+);
tree[rt].w=tree[rt*].w+tree[rt*+].w;
} void query(int rt){
if(tree[rt].l==tree[rt].r){
ans=tree[rt].w;
return;
}
if(tree[rt].mark) pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/;
if(res<=mid) query(rt*);
else query(rt*+);
} int main(){
scanf("%d",&n);
for(int i=;i<=n;i++){
scanf("%d",&a[i]);
}
build(,n,);
scanf("%d",&m);
for(int i=;i<=m;i++){
scanf("%d",&op);
if(op==){
scanf("%d%d%d",&x,&y,&v);
update();
}
if(op==){
ans=;
scanf("%d",&res);
query();
printf("%d\n",ans);
}
} return ;
}
上一篇:Spring Boot笔记一


下一篇:Android百度地图开发(一)环境搭建