【莫队】luogu_2709 小B的询问

题意

∑ c i 2 \sum{{c_i}^2} ci2的值,其中 i i i的值从 1 1 1 K K K,其中 c i c_i ci表示数字 i i i [ L . . R ] [L..R] [L..R]中的重复次数。

思路

莫队修改一下暴力中的两个函数即可,注意 l l l 1 1 1开始,否则会多无用计算。

代码

#include<cmath>
#include<cstdio>
#include<algorithm>

struct node {
	int l, r, pos;
}que[500001];
int n, m, k, block, ans;
int a[500001], cnt[1000001], res[500001];

bool operator <(const node &x, const node &y) {
	return (x.l / block) ^ (y.l / block) ? x.l < y.l : (((x.l / block) & 1) ? x.r < y.r : x.r > y.r);
}

void add(int x) {
	ans += 2 * cnt[a[x]] + 1;
	cnt[a[x]]++;
}

void del(int x) {
	ans -= 2 * cnt[a[x]] - 1;
	cnt[a[x]]--;
}

int main() {
	scanf("%d %d %d", &n, &m, &k);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]);
	block = n / sqrt(m * 2 / 3);
	for (int i = 1; i <= m; i++)
		scanf("%d %d", &que[i].l, &que[i].r), que[i].pos = i;
	std::sort(que + 1, que + m + 1);
	int l = 1, r = 0;
	for (int i = 1; i <= m; i++) {
		int ql = que[i].l, qr = que[i].r;
        while (l < ql) del(l++);
        while (l > ql) add(--l);
        while (r < qr) add(++r);
        while (r > qr) del(r--);
        res[que[i].pos] = ans;
	}
	for (int i = 1; i <= m; i++)
		printf("%d\n", res[i]);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值