社区讨论

最后3个点WA,输出负数?

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

讨论操作

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

当前回复
5 条
当前快照
1 份
快照标识符
@loavjcop
此快照首次捕获于
2023/10/29 10:50
2 年前
此快照最后确认于
2023/11/02 10:56
2 年前
查看原帖
已开longlong,求调玄关。
CPP
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=8e5+10;
int n,m,opt,x,y;
ll a[N],tag[N],k;
struct TreeNode{
	int L,R;
	ll sum;
}tree[N];
ll build(int L,int R,int loc)
{
	if(L>R)
		return 0;
	tree[loc].L=L,tree[loc].R=R;
	if(L==R)
		return tree[loc].sum=a[L];
	return tree[loc].sum=build(L,(L+R)/2,loc*2)+build((L+R)/2+1,R,loc*2+1);
}
void add(int L,int R,int loc,ll k)
{
	if(tree[loc].L>=L&&tree[loc].R<=R)
	{
		tree[loc].sum+=1ll*(tree[loc].R-tree[loc].L+1)*k;
		tag[loc]+=k;
	}
	else
	{
		if(tag[loc]&&tree[loc].L!=tree[loc].R)
		{
			tag[loc*2]+=tag[loc];
			tag[loc*2+1]+=tag[loc];
			tree[loc*2].sum+=1ll*tag[loc]*(tree[loc*2].R-tree[loc*2].L+1);
			tree[loc*2+1].sum+=1ll*tag[loc]*(tree[loc*2+1].R-tree[loc*2+1].L+1);
			tag[loc]=0;
		}
		if(tree[loc*2].R>=L)
			add(L,R,loc*2,k);
		if(tree[loc*2+1].L<=R)
			add(L,R,loc*2+1,k);
		tree[loc].sum=tree[loc*2].sum+tree[loc*2+1].sum; 
	}
	return;
}
ll inquire(int L,int R,int loc)
{
	if(tree[loc].L>=L&&tree[loc].R<=R)
		return tree[loc].sum;
	if(tag[loc]&&tree[loc].L!=tree[loc].R)
	{
		tag[loc*2]+=tag[loc];
		tag[loc*2+1]+=tag[loc];
		tree[loc*2].sum+=1ll*tag[loc]*(tree[loc*2].R-tree[loc*2].L+1);
		tree[loc*2+1].sum+=1ll*tag[loc]*(tree[loc*2+1].R-tree[loc*2+1].L+1);
		tag[loc]=0;
	}
	int ret=0;
	if(tree[loc*2].R>=L)
		ret+=inquire(L,R,loc*2);
	if(tree[loc*2+1].L<=R)
		ret+=inquire(L,R,loc*2+1);
	return ret;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	build(1,n,1);
	while(m--)
	{
		cin>>opt>>x>>y;
		if(opt==1)
		{
			cin>>k;
			add(x,y,1,k);
		}
		else
			cout<<inquire(x,y,1)<<'\n';
	}
	return 0;
}


回复

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

正在加载回复...