数列分块入门 1(LibreOj-6277)
【题目描述】
给出一个长为 n 的数列,以及 n 个操作,操作涉及区间加法,单点查值。
【输入格式】
第一行输入一个数字 n。
第二行输入 n 个数字,第 i 个数字为 ai,以空格隔开。
接下来输入 n 行询问,每行输入四个数字 opt、l、r、c,以空格隔开。
若 opt=0,表示将位于 [l,r] 的之间的数字都加 c。
若 opt=1,表示询问 a[r] 的值(l 和 c 忽略)。
【输出格式】
对于每次询问,输出一行一个数字表示答案。
【样例】
样例输入
4
1 2 2 3
0 1 3 1
1 0 1 0
0 1 2 2
1 0 2 0样例输出
2
5【数据范围与提示】
对于 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 = 100000+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;
int block;//block为块的长度
int a[N];//存放数列元素
int pos[N],tag[N];//pos记录第i个元素在第几个块中,tag为操作标记
void add(int L,int R,int x){
for(int i=L;i<=min(pos[L]*block,R);i++)//统计左区间
a[i]+=x;
if(pos[L]!=pos[R])//如果存在右区间才遍历,防止重复计算
for(int i=(pos[R]-1)*block+1;i<=R;i++)//统计右区间
a[i]+=x;
for(int i=pos[L]+1;i<=pos[R]-1;i++)//统计整块区间
tag[i]+=x;
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
block=sqrt(n);//块的长度
for(int i=1;i<=n;i++)//第i个元素在第几块中
pos[i]=(i-1)/block+1;
for(int i=1;i<=n;i++){
int op;
int left,right,x;
scanf("%d",&op);
scanf("%d%d%d",&left,&right,&x);
if(op==0)
add(left,right,x);
else
printf("%d\n",a[right]+tag[pos[right]]);
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)