CODE[VS] 1080 线段树练习(单值修改、区间求和)

本文介绍了一种基于线段树的数据结构实现,用于解决单值修改与区间求和问题。通过实例演示了如何构建线段树、更新节点值及查询指定区间的和。适用于初学者了解线段树的基本原理及其应用。






http://codevs.cn/problem/1080/










分析:

单值修改、区间求和     入门题目










AC代码:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include<list>
#include <bitset>
#include <climits>
#include <algorithm>
#define gcd(a,b) __gcd(a,b)
#define FIN	freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
typedef long long LL;
const LL mod=1e9+7;
const int INF=0x3f3f3f3f;
const int MAX=1e6+5;
const double PI=acos(-1.0);
using namespace std;
LL a[MAX];
struct Tree{
	int l,r;
	LL val;
}T[MAX];
void build(int rt,int l,int r){//     建树
	T[rt].l=l;
	T[rt].r=r;
	if (l==r) {
		T[rt].val=a[l];
		return ;
	}
	int mid=(l+r)/2;
	build(rt*2,l,mid);
	build(rt*2+1,mid+1,r);
	T[rt].val=T[rt*2].val+T[rt*2+1].val;
}
void update(int rt,int index,int e){//     单值修改
	if (T[rt].l==T[rt].r){
        if (T[rt].l==index)
		T[rt].val+=e;
		return ;
	}
	int mid=(T[rt].l+T[rt].r)/2;
	if (index<=mid) update(rt*2,index,e);
	else update(rt*2+1,index,e);
	T[rt].val=T[rt*2].val+T[rt*2+1].val;
}
LL Query (int rt,int Ql,int Qr){//    查询
	if (T[rt].l>=Ql&&T[rt].r<=Qr) return T[rt].val;
	int mid=(T[rt].l+T[rt].r)/2;
	LL ans=0;
	if (Ql<=mid) ans+=Query(rt*2,Ql,Qr);
	if (Qr>mid) ans+=Query(rt*2+1,Ql,Qr);
	return ans;
}
int main (){
    int n;
	while(scanf ("%d",&n)!=EOF){
		for (int i=1;i<=n;i++) scanf ("%lld",&a[i]);
		build(1,1,n);
		int m;
		scanf ("%d",&m);
        while (m--){
            int x;
            scanf ("%d",&x);
            if (x==1){
                int s,v;
                scanf ("%d%d",&s,&v);
                update(1,s,v);
            }
            else{
                int s,e;
                scanf ("%d%d",&s,&e);
                printf ("%lld\n",Query(1,s,e));
            }
        }

	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值