线段树速撸

点我飞去垃圾模板题

第一次尝试速撸线段树,只撸了个区间修改 区间查询的比较菜的线段树

用时17:33.5

第一遍测样例错了,仔细看了看发现change字数后没有pushup

#include<iostream>
#include<cstdio>
#include<cstring>
#define LL long long
#define pushup(rt) tree[rt]=tree[rt<<1]+tree[rt<<1|1]
using namespace std;

inline void inl(LL &p,char c=getchar(),bool f=0)
{
	while((c<'0' or c>'9') and c!='-')
		c=getchar();
	p=0;
	if(c=='-')
		f=1,c=getchar();
	while(c>='0' and c<='9')
		p=p*10+c-'0',c=getchar();
	if(f)
		p=-p;
}
inline void in(int &p,char c=getchar(),bool f=0)
{
	while((c<'0' or c>'9') and c!='-')
		c=getchar();
	p=0;
	if(c=='-')
		f=1,c=getchar();
	while(c>='0' and c<='9')
		p=p*10+c-'0',c=getchar();
	if(f)
		p=-p;
}

int n,m;
LL tree[100001<<2],add[100001<<2],a[100001];

inline void build(int rt,int l,int r)
{
	if(l==r)
	{
		tree[rt]=a[l];
		return ;
	}
	int m=(l+r)>>1;
	build(rt<<1,l,m);
	build(rt<<1|1,m+1,r);
	pushup(rt);
}
inline void pushdown(int rt,int ln,int rn)
{
	if(add[rt])
		add[rt<<1]+=add[rt],
		add[rt<<1|1]+=add[rt],
		tree[rt<<1]+=add[rt]*ln,
		tree[rt<<1|1]+=add[rt]*rn,
		add[rt]=0;
}
inline void change(int rt,int L,int R,int l,int r,int x)
{
	if(L<=l and R>=r)
	{
		add[rt]+=x;
		tree[rt]+=x*(r-l+1);
		return ;
	}
	int m=(l+r)>>1;
	pushdown(rt,m-l+1,r-m);
	if(L<=m)
		change(rt<<1,L,R,l,m,x);
	if(R>m)
		change(rt<<1|1,L,R,m+1,r,x);
	pushup(rt);
}
inline LL getans(int rt,int L,int R,int l,int r)
{
	if(L<=l and R>=r)
		return tree[rt];
	int m=(l+r)>>1;
	pushdown(rt,m-l+1,r-m);
	LL ans=0;
	if(L<=m)
		ans+=getans(rt<<1,L,R,l,m);
	if(R>m)
		ans+=getans(rt<<1|1,L,R,m+1,r);
	return ans;
}

int main()
{
	in(n);in(m);
	for(LL i=1;i<=n;i++)
		inl(a[i]);
	build(1,1,n);
	while(m--)
	{
		int caozuo;
		in(caozuo);
		if(caozuo==1)
		{
			int l,r,x;
			in(l),in(r),in(x);
			change(1,l,r,1,n,x);
		}
		else
		{
			int l,r;
			in(l),in(r);
			printf("%lld
",getans(1,l,r,1,n));
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/syhien/p/7786459.html