分块算法<1>

18 篇文章 0 订阅
2 篇文章 0 订阅

分块思想:

本质上是暴力,但是用一种巧妙的办法将要暴力的长度为 n n n 的区间划分为 n \sqrt n n 块,并在每一个块中进行总体打标记,最后结果就是将各个标记统一运算。

1、区间修改单点查询 - 代码


#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
#include <utility>

#define Mp(X, Y) std::make_pair(X, Y)
#define debug(X) std::cout << #X << " : " << X << std::endl
#define lson ((rt) << (1))
#define rson ((rt) << 1 | 1)
#define mid (l + r >> 1)
#define lowbit(X) ((X) & (-X))

typedef long long ll;
typedef std::pair<int, int> pii;

ll nextInt()
{
	ll num = 0;
	char c;
	bool flag = false;
	while ((c = std::getchar()) == ' ' || c == '\r' || c == '\t' || c == '\n');
	if (c == '-')
		flag = true;
	else
		num = c - 48;
	while (std::isdigit(c = std::getchar()))
		num = num * 10 + c - 48;
	return (flag ? -1 : 1) * num;
}

const size_t _Siz = 114514;
int L[_Siz] = { 0 }, R[_Siz] = { 0 }, a[_Siz] = { 0 }, pos[_Siz] = { 0 }, add[_Siz] = { 0 };

void change(const int l, const int r, const int c)
{
	int ql = pos[l], qr = pos[r];
	if (ql == qr)
	{
		for (int i = l; i <= r; i++)
			a[i] += c;
	} 
	else
	{
		for (int i = l; i <= R[ql]; i++)
			a[i] += c;
		for (int i = L[qr]; i <= r; i++)
			a[i] += c;
		for (int i = ql + 1; i <= qr - 1; i++)
			add[i] += c;
	}
}

int main(int argc, char **argv)
{
	int n = nextInt();
	for (int i = 1; i <= n; i++)
		a[i] = nextInt();
	// 分成sqrt(n)块
	int t = std::sqrt(n);
	for (int i = 1; i <= t; i++)
	{
		L[i] = (i - 1) * t + 1;
		R[i] = i * t + 1;
	}
	if (R[t] < n)
	{
		t++;
		L[t] = R[t - 1] + 1;
		R[t] = n;
	}
	// 标位置
	for (int i = 1; i <= t; i++)
		for (int j = L[i]; j <= R[i]; j++)
			pos[j] = i;
	// 主体
	for (int i = 1; i <= n; i++)
	{
		int opt = nextInt(), l = nextInt(), r = nextInt(), c = nextInt();
		if (!opt)
		{
		//	int c = nextInt();
			change(l, r ,c);
		}
		else
		{
			int q = pos[r];
			std::cout << add[q] + a[r] << "\n";
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值