分块
模板(区间修改单点查询)
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int n;
int a[1000005];
int lazy[4000005];
int bg[400005];
int bel[400005];
int p_blo;
int sum[400005];
int main()
{
scanf("%d",&n);
p_blo=sqrt(n);
int cnt=0;
int num=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=n;i++)
{
if(cnt==0)
{
num++;
bg[num]=i;
}
bel[i]=num;
sum[num]+=a[i];
cnt++;
if(cnt==p_blo)cnt=0;
}
for(int i=1;i<=n;i++)
{
int opt,l,r,c;
scanf("%d%d%d%d",&opt,&l,&r,&c);
if(opt==0)
{
if(r-l<=p_blo)
{
for(int j=l;j<=r;j++)
a[j]+=c;
continue;
}
int ll=bg[bel[l]+1];
int rr=bg[bel[r]];
for(int j=l;j<ll;j++)
{
a[j]+=c;
sum[bel[j]]+=c;
}
for(int j=rr;j<=r;j++)
{
a[j]+=c;
sum[bel[j]]+=c;
}
for(int j=bel[ll];j<bel[rr];j++)
{
lazy[j]+=c;
sum[j]+=c*(bg[j+1]-bg[j]);
}
}
else
{
long long ans=0ll;
if(r-l<=p_blo)
{
for(int j=l;j<=r;j++)
{
ans+=a[j]+lazy[bel[j]];
}
printf("%lld\n",1ll*ans%(c+1));
continue;
}
int ll=bg[bel[l]+1];
int rr=bg[bel[r]];
for(int j=l;j<ll;j++)
{
ans+=a[j]+lazy[bel[j]];
}
for(int j=rr;j<=r;j++)
ans+=a[j]+lazy[bel[j]];
for(int j=bel[ll];j<bel[rr];j++)
ans+=sum[j];
//cout<<ans<<endl;
printf("%lld\n",1ll*ans%(c+1));
}
}
return 0;
}
区间修改区间查询
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int n;
int a[1000005];
int lazy[4000005];
int bg[400005];
int bel[400005];
int p_blo;
int sum[400005];
int main()
{
scanf("%d",&n);
p_blo=sqrt(n);
int cnt=0;
int num=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=n;i++)
{
if(cnt==0)
{
num++;
bg[num]=i;
}
bel[i]=num;
sum[num]+=a[i];
cnt++;
if(cnt==p_blo)cnt=0;
}
for(int i=1;i<=n;i++)
{
int opt,l,r,c;
scanf("%d%d%d%d",&opt,&l,&r,&c);
if(opt==0)
{
if(r-l<=p_blo)
{
for(int j=l;j<=r;j++)
a[j]+=c;
continue;
}
int ll=bg[bel[l]+1];
int rr=bg[bel[r]];
for(int j=l;j<ll;j++)
{
a[j]+=c;
sum[bel[j]]+=c;
}
for(int j=rr;j<=r;j++)
{
a[j]+=c;
sum[bel[j]]+=c;
}
for(int j=bel[ll];j<bel[rr];j++)
{
lazy[j]+=c;
sum[j]+=c*(bg[j+1]-bg[j]);
}
}
else
{
long long ans=0ll;
if(r-l<=p_blo)
{
for(int j=l;j<=r;j++)
{
ans+=a[j]+lazy[bel[j]];
}
printf("%lld\n",1ll*ans%(c+1));
continue;
}
int ll=bg[bel[l]+1];
int rr=bg[bel[r]];
for(int j=l;j<ll;j++)
{
ans+=a[j]+lazy[bel[j]];
}
for(int j=rr;j<=r;j++)
ans+=a[j]+lazy[bel[j]];
for(int j=bel[ll];j<bel[rr];j++)
ans+=sum[j];
//cout<<ans<<endl;
printf("%lld\n",1ll*ans%(c+1));
}
}
return 0;
}
浙公网安备 33010602011771号