题解 DTOJ #1667.小B的询问(query)

欢迎访问 My Luogu Space。


【题目大意】

一段序列,每次询问 [ l , r ] [l, r] [l,r] 范围内的每个数字的出现次数的平方和。

【题解】

莫队

非常模板的莫队题。

推出 ( n + 1 ) 2 − n 2 = 2 n + 1 (n+1)^2-n^2=2n+1 (n+1)2n2=2n+1(n为数字的出现次数);
意思是一个数字的出现次数多一次会对答案造成多少贡献。

分块分为 n \sqrt{n} n 个。

【代码】

// output format !!
// long long !!
#include 
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 50000+10;
int bol;
struct Q{
	int l, r, id;
	bool operator<(Q a)const{
		return (r/bol==a.r/bol) ? l<a.l : r<a.r;
	}
}q[MAXN];

int n, m, k;
int cnt[MAXN], s[MAXN];
LL ans, Ans[MAXN];

int main(){
	scanf("%d%d%d", &n, &m, &k);
	bol = sqrt(n);
	for(int i=1; i<=n; ++i) scanf("%d", s+i);
	for(int i=1; i<=m; ++i) scanf("%d%d", &q[i].l, &q[i].r), q[i].id = i;
	std::sort(q+1, q+m+1);
	int L = 1, R = 0;
	for(int i=1; i<=m; ++i){
		while(R-1 >= q[i].r) ans -= 1ll*cnt[s[R]]*2-1, --cnt[s[R--]];
		while(R+1 <= q[i].r) ans += 1ll*cnt[s[++R]]*2+1, ++cnt[s[R]];
		while(L+1 <= q[i].l) ans -= 1ll*cnt[s[L]]*2-1, --cnt[s[L++]];
		while(L-1 >= q[i].l) ans += 1ll*cnt[s[--L]]*2+1, ++cnt[s[L]];
		Ans[q[i].id] = ans;
	}
	for(int i=1; i<=m; ++i) printf("%lld\n", Ans[i]);
	return 0;
}

你可能感兴趣的:(题解)