NOIP提高组——线段树

来源:互联网 发布:java final 变量 回收 编辑:程序博客网 时间:2024/05/16 05:18


提高组有一些与普及组截然不同的算法,例如线段树和树状数组。

codevs和洛谷上有许多题目。

现在实现最基本的线段树输入输出。

首先初始化

#include<bits/stdc++.h>using namespace std;#define LL long longconst int MAXN = 100000;
int s[4*MAXN];int add[4*MAXN];
不解释。

然后是更新模块,每次操作后的更新。

void up(int p){    s[p]=s[p*2]+s[p*2+1];}
接着是建树过程

void build(int p,int l,int r){  if(l==r){    scanf("%d",s[p]);  }  int m=(l+r)>>1;  build(p*2,l,m);  build(p*2+1,m+1,r);  up(p);}
然后是更新(增加)

void update(int p,int l,int r,int x,int v){  if(l==r){    s[p]+=v;    return ;  }int m=(l+r)/2;  if(x<=m) update(p*2,l,m,x,v);    else update(p*2+1,m+1,r,x,v);  up(p);}
最后是查询
LL query(int p,int l,int r,int x,int y){  if(x<=l&&r<=y){    return s[p];  }  LL ret=0;  int m=(l+r)/2;  if(x>=m) ret+=query(p*2,l,m,x,y);  if(y<m) ret+=query(p*2+1,m+1,r,x,y);  return ret;}

这个是求区间和,如果是区间最值

ret=max(ret,---);

up

改为 s[p]=max(s[p*2],s[p*2+1]);



原创粉丝点击