您的位置:首页 > 其它

线段树 模板

2015-11-24 14:55 253 查看
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <queue>
#include <iomanip>
#include <string>
#include <ctime>
#include <list>
#include <bitset>
typedef unsigned char byte;
#define pb push_back
#define input_fast std::ios::sync_with_stdio(false);std::cin.tie(0)
#define local freopen("in.txt","r",stdin)
#define pi acos(-1)

using namespace std;

typedef int SgTreeDataType;
struct treenode
{
int L , R  ;
SgTreeDataType sum , lazy;
void updata(SgTreeDataType v)
{
sum += (R-L+1)*v;
lazy += v;
}
};

treenode tree[1500];

inline void push_down(int o)
{
SgTreeDataType lazyval = tree[o].lazy;
tree[2*o].updata(lazyval) ; tree[2*o+1].updata(lazyval);
tree[o].lazy = 0;
}

inline void push_up(int o)
{
tree[o].sum = tree[2*o].sum + tree[2*o+1].sum;
}

inline void build_tree(int L , int R , int o)
{
tree[o].L = L , tree[o].R = R,tree[o].sum = tree[o].lazy = 0;
if (R > L)
{
int mid = (L+R) >> 1;
build_tree(L,mid,o*2);
build_tree(mid+1,R,o*2+1);
}
}

inline void updata(int QL,int QR,SgTreeDataType v,int o)
{
int L = tree[o].L , R = tree[o].R;
if (QL <= L && R <= QR) tree[o].updata(v);
else
{
push_down(o);
int mid = (L+R)>>1;
if (QL <= mid) updata(QL,QR,v,o*2);
if (QR >  mid) updata(QL,QR,v,o*2+1);
push_up(o);
}
}

inline SgTreeDataType query(int QL,int QR,int o)
{
int L = tree[o].L , R = tree[o].R;
if (QL <= L && R <= QR) return tree[o].sum;
else
{
push_down(o);
int mid = (L+R)>>1;
SgTreeDataType res = 0;
if (QL <= mid) res += query(QL,QR,2*o);
if (QR > mid) res += query(QL,QR,2*o+1);
push_up(o);
return res;
}
}

int main(int argc,char *argv[])
{

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: