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+10;
int n,m,x,y,v,res,ans,op;
int a[maxn];

struct node{
    int l,r,w,mark;
}tree[maxn<<2];

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)/2;
    build(l,mid,rt*2);
    build(mid+1,r,rt*2+1);
    tree[rt].w=tree[rt*2].w+tree[rt*2+1].w;
}

void pushdown(int rt){
    tree[rt*2].mark+=tree[rt].mark;
    tree[rt*2+1].mark+=tree[rt].mark;
    tree[rt*2].w+=tree[rt].mark*(tree[rt*2].r-tree[rt*2].l+1);
    tree[rt*2+1].w+=tree[rt].mark*(tree[rt*2+1].r-tree[rt*2+1].l+1);
    tree[rt].mark=0;
}

void update(int rt){
    if(tree[rt].l>=x && tree[rt].r<=y){
        tree[rt].w+=v*(tree[rt].r-tree[rt].l+1);
        tree[rt].mark+=v;
        return;
    }
    if(tree[rt].mark) pushdown(rt);
    int mid=(tree[rt].l+tree[rt].r)/2;
    if(x<=mid) update(rt*2);
    if(y>mid) update(rt*2+1);
    tree[rt].w=tree[rt*2].w+tree[rt*2+1].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)/2;
    if(res<=mid) query(rt*2);
    else query(rt*2+1);
}

int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    build(1,n,1);
    scanf("%d",&m);
    for(int i=1;i<=m;i++){
        scanf("%d",&op);
        if(op==1){
            scanf("%d%d%d",&x,&y,&v);
            update(1);
        }
        if(op==2){
            ans=0;
            scanf("%d",&res);
            query(1);
            printf("%d
",ans);
        }
    }

    return 0;
}
原文地址:https://www.cnblogs.com/whdsunny/p/10457543.html