2019.2.16线段树模板

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
const int maxen=5000;
int a[maxen+5],st[(maxen<<2)+5]; //a函数为主函数读入的数组,st为需要查询的数的信息,树的空间大小的四倍;
void build(int o,int l,int r){ //o为当前需要建立的节点,l为左端点,r为右端点
if(l==r){
st[o]=a[l]; //当左端点与右端点相同时,即为叶子节点,直接赋值即可;
}
else{
int m=l+((r-l)>>1); //m为中间点,左儿子为[l,m],右儿子为[m+1,r];
build(o<<1,l,m); //构建左儿子节点
build((o<<1)|1,m+1,r);//构建右儿子节点
st[o]=st[o<<1]+st[(o<<1)|1];//递归返回时用儿子结点更新父节点,此处可进行更新最大值、最小值、区间和等操作
}
}
int main(){
build(1,1,n);
}

猜你喜欢

转载自www.cnblogs.com/pipihoudewo/p/10389799.html
今日推荐