分块入门

分块——一巴掌把题拍扁的算法

就是把序列分成块,每块内部暴力处理,外部打标记的算法

时间往往是n*(m+n/m)很容易得出当m=根号n是最小

所以n<=1e5时往往适用

 

ORZ hzwer

https://loj.ac/problem/6277

题目描述

给出一个长为 nnn 的数列,以及 nnn 个操作,操作涉及区间加法,单点查值。

输入格式

第一行输入一个数字 nnn。

第二行输入 nnn 个数字,第 iii 个数字为 aia_ia​i​​,以空格隔开。

接下来输入 nnn 行询问,每行输入四个数字 opt\mathrm{opt}opt、lll、rrr、ccc,以空格隔开。

若 opt=0\mathrm{opt} = 0opt=0,表示将位于 [l,r][l, r][l,r] 的之间的数字都加 ccc。

若 opt=1\mathrm{opt} = 1opt=1,表示询问 ara_ra​r​​ 的值(lll 和 ccc 忽略)。

输出格式

对于每次询问,输出一行一个数字表示答案。

样例

样例输入

4
1 2 2 3
0 1 3 1
1 0 1 0
0 1 2 2
1 0 2 0

样例输出

2
5

数据范围与提示

对于 100% 100\%100% 的数据,1≤n≤50000,−231≤others 1 \leq n \leq 50000, -2^{31} \leq \mathrm{others}1≤n≤50000,−2​31​​≤others、ans≤231−1 \mathrm{ans} \leq 2^{31}-1ans≤2​31​​−1。

 

吐槽一下:从输出描述可以看出这题目出的多随意)

如果加的区间包含块,就标记下,如果不包含,暴力修改

时间O(n根号n),优秀

#include<cstdio>
#include<cmath>
#define ll long long
using namespace std;

int read()
{
	int ret=0; bool f=0;
	char ch=getchar();
	while(ch<'0'||ch>'9') 
	{
		if(ch=='-') f=1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
		ret=(ret<<1)+(ret<<3)+ch-'0',ch=getchar();
	return f?-ret:ret;
}

const int N=1e5+5;
int id[N],n;

struct A
{
	int num;
	ll a[N],t[N];
	inline void pre()
	{
		num=sqrt(n);
		for(int i=1;i<=n;i++)
			id[i]=(i-1)/num+1,a[i]=read();
	}	
	
	inline void add(int l,int r,int c)
	{
		for(int i=id[l]+1;i<=id[r]-1;i++) t[i]+=c;
		if(id[l]==id[r]) 
		{
			for(int i=l;i<=r;i++) a[i]+=c;
			return;
		}
		for(int i=l;i<=num*id[l];i++) 
			a[i]+=c;
		for(int i=num*(id[r]-1)+1;i<=r;i++)
			a[i]+=c;
	}
	
	inline ll sum(int x) 
	{
		return a[x]+t[id[x]];
	}
}fk;

int main()
{
	n=read();
	fk.pre();
	for(int i=1;i<=n;i++)
	{
		int t=read(),l=read(),r=read(),c=read();
		if(!t) fk.add(l,r,c);
			else printf("%lld\n",fk.sum(r));
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值