[BZOJ3809] Gty的二逼妹子序列(莫队 + 值域分块)

博客介绍了如何利用莫队算法和值域分块技术解决一个序列中区间数值域在特定范围内的计数问题。在处理n个元素,q次询问的场景下,通过均值法优化,将复杂度降低到O(nq),避免了使用树状数组导致的O(nqlogn)复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

  • 给你一个长度为 n n n 的序列 a a a q q q 次询问,每次询问一段区间 [ l , r ] [l,r] [l,r] 内有多少种数值域在 [ x , y ] [x,y] [x,y] 内(值相等的数算同一种)( a i ≤ n ≤ 1 0 5 , q ≤ 1 0 6 a_i\le n\le10^5,q\le 10^6 ain105,q106)。

没有修改自然考虑莫队,按一般的方法我们要会插入删除 n q n \sqrt q nq 次,询问 q q q 次,如果用树状数组维护的话复杂度是 O ( n q log ⁡ n ) O(n\sqrt q\log n) O(nq logn)的。

我们发现询问次数与插入删除次数及其不对称,考虑用均值法优化,增大询问复杂度来减小修改复杂度,那么只需要值域分块即可,复杂度 O ( n q ) O(n \sqrt q) O(nq )

#include <bits/stdc++.h>

#define For(i, a, b) for (int i = a; i <= b; ++ i)

using namespace std;

inline int read()
{
	int _ = 0, __ = getchar(), ___ = 1; 
	for (; !isdigit(__); __ = getchar()) if (__ == '-') ___ = -1;
	for (; isdigit(__); __ = getchar()) _ = (_ << 3) + (_ << 1) + (__ ^ 48);
	return _ * ___;
}

const int N = 1e5 + 5;

int a[N], be[N], rel[N];
int st[N], ed[N], cnt;

struct Que { int id, l, r, x, y; } Q[N * 10];

bool cmp(Que A, Que B) { return rel[A.l] == rel[B.l] ? A.r < B.r : A.l < B.l; }

int cnt1[N], cnt2[N];

void Insert(int pos) { if (++ cnt1[a[pos]] == 1) ++ cnt2[be[a[pos]]]; }
void Delete(int pos) { if (-- cnt1[a[pos]] == 0) -- cnt2[be[a[pos]]]; }

int Query(int l, int r)
{
	int res = 0;
	if (be[l] + 1 <= be[r] - 1)
	{
		For(i, be[l] + 1, be[r] - 1) res += cnt2[i];
		For(i, l, ed[be[l]]) res += cnt1[i] != 0;
		For(i, st[be[r]], r) res += cnt1[i] != 0;
	}
	else For(i, l, r) res += cnt1[i] != 0;
	return res;
}

int main()
{
	static int ans[N * 10], n = read(), q = read(), sz1, sz2;
	sz1 = sqrt(n), sz2 = sqrt((double)n * n / q);
	For(i, 1, n) 
	{
		if (i % sz1 == 1) st[++ cnt] = i;
		if (i % sz1 == 0 || i == n) ed[cnt] = i;
		a[i] = read(), be[i] = cnt, rel[i] = i / sz2;
	}
	For(i, 1, q) 
	{
		Q[i].id = i;
		Q[i].l = read(), Q[i].r = read();
		Q[i].x = read(), Q[i].y = read();
	}
	sort(Q + 1, Q + q + 1, cmp);
	int l = 1, r = 0;
	For(i, 1, q)
	{
		while (r < Q[i].r) Insert(++ r);
		while (r > Q[i].r) Delete(r --);
		while (l > Q[i].l) Insert(-- l);
		while (l < Q[i].l) Delete(l ++);
		ans[Q[i].id] = Query(Q[i].x, Q[i].y);
	}
	For(i, 1, q) printf("%d\n", ans[i]);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值