Codeforces 86D.Powerful array(莫队)

Powerful array

题目

An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.

You should calculate the power of t given subarrays.

Input

First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly.

Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array.

Next t lines contain two positive integers lr (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray.

Output

Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray.

Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d)

 题目大意

给出n个数,m组询问,每组询问给出一段区间,输出区间内每个位置的val和,val的定义为该位置的数的值乘该位置上的数在区间内出现过的次数的平方。

思路

莫队板子题,对每个区间的数进行扫过去暴力维护

主要是没怎么写过莫队,或者说没怎么写出过莫队

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+100;

struct Query {
	int l,r,id,pos;
	bool operator<(const Query &x)const {
		if(pos!=x.pos)return pos<x.pos;
		return r<x.r;
		//return (pos^x.pos)?pos<x.pos:(pos&1)?r<x.r:r>x.r;//奇偶优化
	}
} a[N];
ll b[N];
ll cnt[N],Ans[N];
ll ans=0;
void add(ll x) {
	ans-=cnt[x]*cnt[x]*x;
	cnt[x]++;
	ans+=cnt[x]*cnt[x]*x;
}
void del(ll x) {
	ans-=cnt[x]*cnt[x]*x;
	cnt[x]--;
	ans+=cnt[x]*cnt[x]*x;
}
void solve() {
	int n,m;
	cin>>n>>m;
	int siz=sqrt(n);
	for(int i=1; i<=n; i++)cin>>b[i];
	for(int i=1; i<=m; i++) {
		cin>>a[i].l>>a[i].r;
		a[i].pos=(a[i].l-1)/siz+1;
		a[i].id=i;
	}
	sort(a+1,a+m+1);
	int l=1,r=0;
	for(int i=1; i<=m; i++) {

		while(l>a[i].l) {
			l--;
			add(b[l]);
		}
		while(r<a[i].r) {
			r++;
			add(b[r]);
		}
		while(l<a[i].l) {
			del(b[l]);
			l++;
		}
		while(r>a[i].r) {
			del(b[r]);
			r--;
		}
		Ans[a[i].id]=ans;
	}
	for(int i=1; i<=m; i++) {
		cout<<Ans[i]<<'\n';
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();

	return 0;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心刍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值