数列分块入门 5(LibreOj-6281)
【题目描述】
给出一个长为 n 的数列,以及 n 个操作,操作涉及区间开方,区间求和。
【输入格式】
第一行输入一个数字 n。
第二行输入 n 个数字,第 i 个数字为 ai,以空格隔开。
接下来输入 n 行询问,每行输入四个数字 opt、l、r、c,以空格隔开。
若 opt=0,表示将位于 [l,r] 的之间的数字都开方,对于区间中的每个 ai(l<=i<=r),ai->|√ai|
若 opt=1,表示询问位于 [l,r] 的所有数字的和。
【输出格式】
对于每次询问,输出一行一个数字表示答案。
【样例】
样例输入
4
1 2 2 3
0 1 3 1
1 1 4 4
0 1 2 2
1 1 2 4样例输出
6
2【数据范围与提示】
对于 100% 的数据,1<=n<=50000,-2^31<=other,ans<=2^31-1。
【源代码】
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
LL block,sum;//block为块的长度,sum为块的个数
LL a[N];
LL pos[N];//pos记录第i个元素在第几个块中
LL ans[N];//维护整块和
bool flag[N];//标记整块是否全为1
void init(LL n){
block=sqrt(n);//块的长度
sum=n/block;//块个数
if(n%block)
sum++;
for(LL i=1;i<=n;i++)//第i个元素在第几块中
pos[i]=(i-1)/block+1;
}
void work(LL L,LL R,LL x){//维护整块和
LL start=0;
for(LL i=L;i<=R;i++)
start+=a[i];
ans[x]=start;
}
void update(LL L,LL R){
for(LL i=L;i<=min(pos[L]*block,R);i++){//左边的边角料
ans[pos[L]]-=a[i];//开方前元素和减去第i个元素
a[i]=sqrt(a[i]);//开方
ans[pos[L]]+=a[i];//开方后元素和加上第i个元素
}
if(pos[L]!=pos[R]){//存在右区间才遍历,防止重复计算
for(LL i=(pos[R]-1)*block+1;i<=R;i++){//右边的边角料
ans[pos[R]]-=a[i];//开方前元素和减去第i个元素
a[i]=sqrt(a[i]);//开方
ans[pos[R]]+=a[i];//开方后元素和加上第i个元素
}
}
for(LL i=pos[L]+1;i<=pos[R]-1;i++){//中间的整块
if(flag[i])//全为1,跳过
continue;
else{//不全为1,暴力处理
flag[i]=true;//先假设为1,如果不是后面再改为0
for(int j=(i-1)*block+1;j<=i*block;j++){//块中的所有元素
ans[i]-=a[j];//开方前元素和减去第j个元素
a[j]=sqrt(a[j]);//开方
ans[i]+=a[j];//开方后元素和加上第j个元素
if(a[j]!=1)//不全为1
flag[i]=false;
}
}
}
}
LL query(LL L,LL R){
LL res=0;
for(LL i=L;i<=min(pos[L]*block,R);i++){//左边的边角料
res+=a[i];
}
if(pos[L]!=pos[R]){//存在右区间才遍历,防止重复计算
for(LL i=(pos[R]-1)*block+1;i<=R;i++){//右边的边角料
res+=a[i];
}
}
for(LL i=pos[L]+1;i<=pos[R]-1;i++){//中间的整块进行二分查找
res+=ans[i];
}
return res;
}
int main(){
LL n;
scanf("%lld",&n);
for(LL i=1;i<=n;i++)
scanf("%lld",&a[i]);
init(n);
for(LL i=1;i<=sum;i++)//传入块的左右边界与编号
work((i-1)*block+1,i*block,i);
for(LL i=1;i<=n;i++){
LL op;
LL left,right,x;
scanf("%lld",&op);
scanf("%lld%lld%lld",&left,&right,&x);
if(op==0)
update(left,right);
else if(op==1)
printf("%lld\n",query(left,right));
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)