【莫队】CF220B Little Elephant and Array

题目链接
初学莫队,所以用莫队来解题,但不是计算区间内有几个不同的数,所以稍微修改add和del函数的内部即可
需要注意的是,数组的长度最大为1e5,那么大于1e5的数是不可能满足条件的,所以在函数内部直接return掉(否则会RE,但计数的cnt数组是开不了1e9的)
AC代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6 + 5;
LL aa[N], cnt[N], belong[N],ans[N],now,n,m;
struct node
{
	LL l, r, id;
}q[N];
void add(LL i)
{
	if (aa[i] > N) return; //防止越界,直接return
	if (cnt[aa[i]] == aa[i]) now--;//如果原来相等,那么加入新的数后肯定不相等,答案的数量就-1
	cnt[aa[i]]++; //aa[i]在区间内的数量+1
	if (cnt[aa[i]]==aa[i]) now++; //如果加入后符合条件,答案+1
}
void del(LL i) //同上
{
	if (aa[i] > N) return;
	if (cnt[aa[i]] == aa[i]) now--;
	cnt[aa[i]]--;
	if (cnt[aa[i]]==aa[i]) now++;
}
int cmp(const struct node& a, const struct node& b)
{
	return (belong[a.l] ^ belong[b.l]) ? belong[a.l] < belong[b.l] : ((belong[a.l] & 1) ? a.r < b.r : a.r > b.r);
}
inline LL read() {
	LL x = 0, f = 1; char ch = getchar();
	while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
	while ('0' <= ch && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
	return x * f;
}
inline void printi(LL x) {
	if (x / 10) printi(x / 10);
	putchar(x % 10 + '0');
}
int main()
{
	cin >> n;
	LL sz = sqrt(n);
	m = read();
	for (LL i = 1; i <= n; i++)
	{
		aa[i] = read();
		belong[i] = (i - 1) / sz + 1;
	}
	for (LL i = 1; i <= m; i++)
	{
		q[i].l = read();
		q[i].r = read();
		q[i].id = i;
	}
	sort(q + 1, q + 1 + m, cmp);
	LL l = 1, r = 0;
	for (LL i = 1; i <= m; i++)
	{
		int ql = q[i].l,qr=q[i].r;
		while (l < ql) del(l++);
		while (l > ql) add(--l);
		while (r < qr) add(++r);
		while (r > qr) del(r--);
		ans[q[i].id] = now;
	}
	for (LL i = 1; i <= m; i++)
	{
		printi(ans[i]);
		putchar('\n');
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值