社区讨论

线段树模板写炸求调 QAQ

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

讨论操作

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

当前回复
4 条
当前快照
1 份
快照标识符
@locl3l43
此快照首次捕获于
2023/10/30 15:34
2 年前
此快照最后确认于
2023/11/05 02:45
2 年前
查看原帖
先谢谢大佬们了awa
CPP
#include<cstdio>
#define int long long
using namespace std;
int n,m,tree[100001*4],tag[100001*4],x[100001];
int leftson(int pos)
{
	return pos<<1;
}
int rightson(int pos)
{
	return pos<<1|1;
}
void push_up(int pos)
{
	tree[pos]=tree[leftson(pos)]+tree[rightson(pos)];
}
void build(int pos,int l,int r)
{
	if(l==r)
	{
		tree[pos]=x[l];
		return;
	}
	int m=(l+r)>>1;
	build(leftson(pos),l,m);
	build(rightson(pos),m+1,r);
	push_up(pos);
}
void push_down(int pos,int l,int r)
{
	int m=(l+r)>>1;
	tag[leftson(pos)]+=tag[pos];
	tree[leftson(pos)]+=tag[pos]*(m-l+1);
	tag[rightson(pos)]+=tag[pos];
	tree[rightson(pos)]+=tag[pos]*(r-m);
	tag[pos]=0;
}
void update(int x,int y,int pos,int l,int r,int k)
{
	if(x<=l&&r<=y)
	{
		tag[pos]+=k;
		tree[pos]+=k*(r-l+1);
		return;
	}
	push_down(pos,l,r);
	int m=(l+r)>>1;
	if(x<=m)
		update(x,y,leftson(pos),l,m,k);
	if(y>m)
		update(x,y,rightson(pos),m+1,r,k);
	push_up(pos);
}
int query(int x,int y,int pos,int l,int r)
{
	int ans=0;
	if(x<=l&&r<=y)
		return tree[pos];
	int m=(l+r)>>1;
	push_down(pos,l,r);
	if(x<=m)
		ans+=query(x,y,leftson(pos),l,m);
	if(x>m)
		ans+=query(x,y,rightson(pos),m+1,r);
	return ans;
}
void build()
{
	build(1,1,n);
}
void update(int x,int y,int k)
{
	update(x,y,1,1,n,k);
}
int query(int x,int y)
{
	return query(x,y,1,1,n);
}
signed main()
{
	scanf("%lld %lld",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%lld",&x[i]);
	build();
	for(int i=1;i<=m;i++)
	{
		int op;
		scanf("%lld",&op);
		if(op==1)
		{
			int x,y,k;
			scanf("%lld %lld %lld",&x,&y,&k);
			update(x,y,k);
		}
		if(op==2)
		{
			int x,y;
			scanf("%lld %lld",&x,&y);
			printf("%lld\n",query(x,y));
		}
	}
}

回复

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

正在加载回复...