线段树大红大紫求助
查看原帖
线段树大红大紫求助
1210321
zhangzhixu000001楼主2024/4/23 20:14
#include <bits/stdc++.h>
using namespace std;
#define io ios::sync_with_stdio(0)
const int maxn=5e5;
struct tree{
	int l,r;
	long long sum,tag;
}tr[maxn<<2];
int num[maxn];
inline int ls(int n){return n<<1;}
inline int rs(int n){return n<<1|1;}
inline void up(int n)
{
	tr[n].sum=tr[ls(n)].sum+tr[rs(n)].sum;
	return;
}
inline void build(int l,int r,int p)
{
	tr[p].l=l;tr[p].r=r;
	if (l==r)
	{
		tr[p].sum=num[l];
		return;
	}
	int mid=(l+r)>>1;
	build(l,mid,ls(p));
	build(mid+1,r,rs(p));
	up(p);
}
inline void tagadd(int d,int l,int r,int p)
{
	tr[p].tag+=d;
	tr[p].sum+=d*(r-l+1);	
}
inline void pushdown(int p,int l,int r)
{
	if (tr[p].tag)
	{
		int mid=(l+r)>>1;
		tagadd(tr[p].tag,l,mid,ls(p));
		tagadd(tr[p].tag,mid+1,r,rs(p));
		tr[p].tag=0;
	}
 }
inline int query(int l,int r,int p)
{
 	if (tr[p].l<=l&&tr[p].r<=r) return tr[p].sum;
	pushdown(p,l,r);
	int tot=0;
	if (tr[ls(p)].r>=l) tot+=query(l,r,ls(p));
	if (tr[rs(p)].l<=r) tot+=query(l,r,rs(p));
	return tot; 
} 
inline void updata(int l,int r,int p,int num)
{
	if(tr[p].l>r||tr[p].r<l) return;
	if (tr[p].l>=l&&tr[p].r<=r) 
	{
		tagadd(num,tr[p].l,tr[p].r,p);
		return;
	}
	pushdown(p,tr[p].l,tr[p].r);
	if(tr[ls(p)].r>=l) updata(l,r,ls(p),num);
	if(tr[rs(p)].l<=r) updata(l,r,rs(p),num);
	up(p);
}
int main() {
	io;
	int n,m,a,b,c;cin>>n>>m;
	for (int i=1;i<=n;i++) cin>>num[i];
	build(1,n,1);
	for (int i=1;i<=m;i++)
	{
		cin>>a>>b>>c;
		switch(a)
		{
			case 1:updata(b,b,1,c);break;
			case 2:cout<<query(b,c,1)<<endl;
			default:break;
		 } 
	}
	return 0;
}
2024/4/23 20:14
加载中...