跳到正文

算法·理论

【模板】线段树 单点修改,区间通用

Chenhaorui88约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月11日
更新
2026年4月11日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int M = 4e6 + 1;
struct Node{
  int v = 0;
  Node operator+(const Node &o){//重载运算符加法
    return Node{/*(v+o.v)*/};//要改!!!
  }
}node[M];
void push_up(int p){
  node[p] = node[p << 1] + node[p << 1 | 1];//注意是zuo移
}
// id 是节点在数组中的下标
// L, r 是这个节点所对应的范围
// p 是修改的位置
// x 是修改的值
void update(int id,int l,int r,int p,Node x){
  if(l==r){
    node[id] = /*node[id] + x*/;//也要改!!!!
    return;
  }
  int mid = (l+r)/2;
  if(p <= mid) update(id << 1,l,mid,p,x);
  else update(id << 1 | 1,mid+1,r,p,x);
  push_up(id);
}
// id 是当前节点在数组中的下标
// l,r 表示该节点管理的区间范围
// L, R 是要查询的目标区间范围
Node query(int id,int l,int r,int L,int R){
  if(L <= l&& r <= R)
    return node[id];
  int mid = (l+r)/2;
  Node res;
  if(L <= mid)
    res = res + query(id << 1,l,mid,L,R);
  if(mid < R)
    res = res + query(id << 1 | 1,mid+1,r,L,R);
  return res;
}

int arr[M];
void build(int id,int l,int r){//初始建树,o(n);
  if(l==r){
    node[id] = {arr[l]};
    return;
  }
  int mid = (l+r)/2;
  build(id << 1,l,mid);
  build(id << 1 | 1,mid+1,r);
  push_up(id);
}
signed main(){
    int n,q;
    cin.tie(0)->sync_with_stdio(0);
    cin>>n>>q;
    for(int i = 1;i<=n;i++)
    	cin >> arr[i];
	build(1, 1, n);
    while(q--){
      int op;
      cin>>op;
      if(op==1){
        int p;
        Node x;
        cin>>p>>x.v;
        update(1,1,n,p,x);
      }
      else{
        int L,R;
        cin>>L>>R;
        int ans = query(1,1,n,L,R).v;
        printf("%lld\n",ans);
      }
    }

}
原文