洛谷P2709 小B的询问
? 解题记录 ? ? 洛谷 ? ? 莫队 ?    2018-01-22 16:02:00    673    0    0

题目描述

小B有一个序列,包含N个1~K之间的整数。他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重复次数。小B请你帮助他回答询问。

输入输出格式

输入格式:

 

第一行,三个整数N、M、K。

第二行,N个整数,表示小B的序列。

接下来的M行,每行两个整数L、R。

 

输出格式:

 

M行,每行一个整数,其中第i行的整数表示第i个询问的答案。

 

输入输出样例

输入样例#1: 复制
6 4 3
1 3 2 1 1 3
1 4
2 6
3 5
5 6
输出样例#1: 复制
6
9
5
2

说明

对于全部的数据,1<=N、M、K<=50000

一道比较板的莫队,只是需要把平方贡献展开来更新。

基本思路,把询问看做二维平面上的点,进行上下左右移动。一边移动一边更新答案。如果把平面分块,那么我们可以证明在块长宽为sqrt(n)时最优只需要移动O(n * sqrt(n))次。

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 5e4 + 5, Bsize = 223;
struct Query {
	int l, r, id;
}qs[maxn];
int cnt[maxn], color[maxn], ans[maxn], now, n, m, k, x, y;
bool cmp(const Query &a, const Query &b) {
	if(a.r / Bsize == b.r / Bsize) 
		return a.l / Bsize == b.r / Bsize ? a.r < b.r : a.l < b.l;
	else return a.r < b.r;
}
int main() {
	scanf("%d%d%d", &n, &m, &k);
	for(register int i = 1; i <= n; ++i) scanf("%d", &color[i]);
	for(register int i = 1; i <= m; ++i) 
		scanf("%d%d", &qs[i].l, &qs[i].r), qs[i].id = i;
	sort(qs + 1, qs + m + 1, cmp), now = x = y = 1, ++cnt[color[1]];
	for(register int i = 1; i <= m; ++i) {
		while(x < qs[i].l) now -= cnt[color[x]] * 2 - 1, --cnt[color[x]], ++x;
		while(x > qs[i].l) now += cnt[color[x - 1]] * 2 + 1, ++cnt[color[x - 1]], --x;
		while(y < qs[i].r) now += cnt[color[y + 1]] * 2 + 1, ++cnt[color[y + 1]], ++y;
		while(y > qs[i].r) now -= cnt[color[y]] * 2 - 1, --cnt[color[y]], --y;
		ans[qs[i].id] = now;
	}
	for(register int i = 1; i <= m; ++i)
		printf("%d\n", ans[i]);
	return 0;
}


上一篇: 洛谷P1903 [国家集训队]数颜色

下一篇: 洛谷P3224 [HNOI2012]永无乡

673 人读过
立即登录, 发表评论.
没有帐号? 立即注册
0 条评论
文档导航