蒟蒻的求助(WA*9)
查看原帖
蒟蒻的求助(WA*9)
561945
W_LXA_G楼主2021/12/2 23:03

蒟蒻刚刚学线段树,以下是代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int ls(int x){return x<<1;}
int rs(int x){return x<<1|1;}
const ll maxn=1e+6;
ll sum[maxn],tag[maxn],num[maxn];
void update(int x){
	sum[x]=sum[ls(x)]+sum[rs(x)];
}
void down(int x,int l,int r){
	if (tag[x]){
		tag[ls(x)]=tag[x];
		tag[rs(x)]=tag[x];
		sum[ls(x)]+=((l+r)/2-l+1)*tag[x];
		sum[rs(x)]+=(r-(l+r)/2)*tag[x];
		tag[x]=0;
	}
}
void change(int x,int A,int B,int l,int r,int v){
	if (A<=l&&B>=r){
		sum[x]+=(r-l+1)*v;tag[x]=v;
		return;
	}
	down(x,l,r);
	if (A<=(l+r)/2)change(ls(x),A,B,l,(l+r)/2,v);
	if (B>(l+r)/2)change(rs(x),A,B,(l+r)/2+1,r,v);
	update(x);
	return;
}
ll question(int x,int l,int r,int A,int B){
	if (A<=l&&B>=r)return sum[x];
	down(x,l,r);
	ll res=0;
	if (A<=(l+r)/2)res+=question(ls(x),l,(l+r)/2,A,B);
	if (B>(l+r)/2)res+=question(rs(x),(l+r)/2+1,r,A,B);
	return res;
}
void bulid(int x,int l,int r){
	if (l==r){
		sum[x]=num[l];
		return;
	}
	bulid(ls(x),l,(l+r)/2);
	bulid(rs(x),(l+r)/2+1,r);
	update(x);
	return;
}
int main(){
	int n,m;cin>>n>>m;
	for (int i=1;i<=n;i++)cin>>num[i];
	bulid(1,1,n);
	while (m--){
		int cnt,x,y,k;cin>>cnt>>x>>y;
		if (cnt==2)cout<<question(1,1,n,x,y)<<endl;
		else{
			cin>>k;
			change(1,x,y,1,n,k);
		}
	}
	return 0;
}

样例和第一个点是可以过的

但比如这组数据:

输入:

8 10
659 463 793 740 374 330 772 681 
1 5 8 39
2 5 8
1 3 6 3
1 5 8 90
1 1 5 21
2 3 8
1 3 8 17
1 4 7 52
2 2 6
1 2 7 41

以上代码输出:

2313
4197
3146

答案:

2313
4281
3278

蒟蒻感觉不是很能理解,求教dalao到底哪里出了问题。

(回复的话记得@我)

万分感谢

2021/12/2 23:03
加载中...