IAKIOI66666 @ 2024-07-27 16:34:38
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int n,m,a[100010];
struct node{
int l,r;
long long dat,add;
}tree[400050];
void build(int p,int l,int r)
{
tree[p].l=l,tree[p].r=r;
if(l==r)
{
tree[p].dat=a[l];
return;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
tree[p].dat=tree[p*2].dat+tree[p*2+1].dat;
}
void add(int p)
{
if(tree[p].add)
{
tree[p*2].dat=tree[p].add*(tree[p*2].r-tree[p*2].l+1);
tree[p*2].add+=tree[p].add;
tree[p*2+1].dat=tree[p].add*(tree[p*2+1].r-tree[p*2+1].l+1);
tree[p*2+1].add+=tree[p].add;
tree[p].add=0;
}
}
void change(int p,int l,int r,long long k)
{
if(tree[p].l>=l&&tree[p].r<=r)
{
tree[p].dat+=k*(tree[p].r-tree[p].l+1);
tree[p].add+=k;
return;
}
add(p);
int mid=(tree[p].l+tree[p].r)/2;
if(l<=mid)change(p*2,l,r,k);
if(r>mid)change(p*2+1,l,r,k);
tree[p].dat=tree[p*2].dat+tree[p*2+1].dat;
}
long long ask(int p,int l,int r)
{
if(tree[p].l>=l&&tree[p].r<=r)
{
return tree[p].dat;
}
add(p);
int mid=(tree[p].l+tree[p].r)/2;
long long value=0;
if(l<=mid)value+=ask(p*2,l,r);
if(r>mid)value+=ask(p*2+1,l,r);
return value;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
build(1,1,n);
while(m--)
{
int t,l,r;
long long k;
cin>>t;
if(t==1)
{
cin>>l>>r>>k;
change(1,l,r,k);
}
else
{
cin>>l>>r;
cout<<ask(1,l,r)<<endl;
}
}
return 0;
}
by free_fall @ 2024-07-27 16:39:07
@IAKIOI66666
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int n,m,a[100010];
struct node{
int l,r;
long long dat,add;
}tree[400050];
void build(int p,int l,int r)
{
tree[p].l=l,tree[p].r=r;
if(l==r)
{
tree[p].dat=a[l];
return;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
tree[p].dat=tree[p*2].dat+tree[p*2+1].dat;
}
void add(int p)
{
if(tree[p].add)
{
tree[p*2].dat+=tree[p].add*(tree[p*2].r-tree[p*2].l+1);
tree[p*2].add+=tree[p].add;
tree[p*2+1].dat+=tree[p].add*(tree[p*2+1].r-tree[p*2+1].l+1);
tree[p*2+1].add+=tree[p].add;
tree[p].add=0;
}
}
void change(int p,int l,int r,long long k)
{
if(tree[p].l>=l&&tree[p].r<=r)
{
tree[p].dat+=k*(tree[p].r-tree[p].l+1);
tree[p].add+=k;
return;
}
add(p);
int mid=(tree[p].l+tree[p].r)/2;
if(l<=mid)change(p*2,l,r,k);
if(r>mid)change(p*2+1,l,r,k);
tree[p].dat=tree[p*2].dat+tree[p*2+1].dat;
}
long long ask(int p,int l,int r)
{
if(tree[p].l>=l&&tree[p].r<=r)
{
return tree[p].dat;
}
add(p);
int mid=(tree[p].l+tree[p].r)/2;
long long value=0;
if(l<=mid)value+=ask(p*2,l,r);
if(r>mid)value+=ask(p*2+1,l,r);
return value;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
build(1,1,n);
while(m--)
{
int t,l,r;
long long k;
cin>>t;
if(t==1)
{
cin>>l>>r>>k;
change(1,l,r,k);
}
else
{
cin>>l>>r;
cout<<ask(1,l,r)<<endl;
}
}
return 0;
}
by free_fall @ 2024-07-27 16:40:19
@IAKIOI66666 其实还是挺明显的,你这个dat在add里面应该+=,如果直接覆盖就变成所加的数,而不是加上这个值之后的数了。
by IAKIOI66666 @ 2024-07-27 16:49:16
@free_fall %%%
谢谢大佬,此贴结