社区讨论

WA求解

P3372【模板】线段树 1参与者 4已保存回复 6

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
6 条
当前快照
1 份
快照标识符
@mi7rs0wu
此快照首次捕获于
2025/11/21 02:33
4 个月前
此快照最后确认于
2025/11/21 02:33
4 个月前
查看原帖
CPP
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<iomanip>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<sstream>
#include<cctype>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<ctime>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
using namespace std;
const int INF=2147483647;
/*inline ll read()
{
	ll x=0,k=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')k=-1;c=getchar();}
	while(c>='0'&&c<='9'){x=(x<<3)+(x<<1)+(c^48);c=getchar();}
	return x*k;
}*/
struct node{
	ll v,laz;
}tree[400486];
ll a[100086],n,m,x,y,k,op;
void update(ll root)
{
	tree[root].v=tree[root<<1].v+tree[root<<1|1].v;
}
void build(ll l,ll r,ll root)
{
	tree[root].laz=0;
	if(l==r)
	{
		tree[root].v=a[l];
		return ;
	}
	ll mid=(l+r)>>1;
	build(l,mid,root<<1);
	build(mid+1,r,root<<1|1);
	update(root);
}
void pushdown(ll root,ll len)
{
	tree[root<<1].laz+=tree[root].laz;
	tree[root<<1|1].laz+=tree[root].laz;
	tree[root<<1].v+=tree[root<<1].laz*((len+1)/2);
	tree[root<<1|1].v+=tree[root<<1|1].laz*(len/2);
	tree[root].laz=0;
}
void add(ll l,ll r,ll lnow,ll rnow,ll x,ll root)
{
	if(l<=lnow&&r>=rnow)
	{
		tree[root].laz+=x;
		tree[root].v+=x*(rnow-lnow+1);
		return ;
	}
	if(tree[root].laz)pushdown(root,rnow-lnow+1);
	ll mid=(lnow+rnow)>>1;
	if(l<=mid)add(l,r,lnow,mid,x,root<<1);
	if(r>mid)add(l,r,mid+1,rnow,x,root<<1|1);
	update(root);
}
ll query(ll l,ll r,ll lnow,ll rnow,ll root)
{
	if(l<=lnow&&r>=rnow)
	return tree[root].v;
	if(tree[root].laz)pushdown(root,rnow-lnow+1);
	ll mid=(lnow+rnow)>>1,ans=0;
	if(l<=mid)ans+=query(l,r,lnow,mid,root<<1);
	if(r>mid)ans+=query(l,r,mid+1,rnow,root<<1|1);
	return ans;
}
//void output()
//{
//	rep(i,1,2*n)if(tree[2*i].v==0)printf("%lld ",tree[i].v);
//	printf("\n");
//}
int main()
{
	scanf("%lld%lld",&n,&m);
	rep(i,1,n)scanf("%lld",&a[i]);
	build(1,n,1);
	while(m--)
	{
		scanf("%lld%lld%lld",&op,&x,&y);
		if(op==1)
		{
			scanf("%lld",&k);
			add(x,y,1,n,k,1);
			//output();
		}
		else
		{
			ll t=query(x,y,1,n,1);
			printf("%lld\n",t);
			//output();
		}
	}
	return 0;
}
大佬求助

回复

6 条回复,欢迎继续交流。

正在加载回复...