P2709题解:(分块 + 莫队)

/*//
Problem: P2709 小B的询问
Contest: 莫队
URL: https://www.luogu.com.cn/problem/P2709
/*/
#include <bits/stdc++.h>
#define ll long long int
#define ull unsigned long long int
using namespace std;
const int inf = 0x3f3f3f3f;
const ll ll_inf = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 5;
ll res = 0;
int L = 1, R = 0, block;
int has[5*maxn];
int a[5*maxn];
struct node {
	int lift, right, idx;
}q[5*maxn];

// 该种排序不行
// bool cmp(node x1, node x2) {
// 	if(x1.lift == x2.lift) {
// 		if(x1.right == x2.right) {
// 			return x1.idx < x2.idx;
// 		}
// 		return x1.right < x2.right;
// 	}
// 	return x1.lift < x2.lift;
// }


/*
这里必须要分块, 否则时间超限
*/
 
// 分块排序
inline bool cmp(node x1, node x2) {
	if((x1.lift-1)/block == (x2.lift-1)/block) {
		return x1.right < x2.right;
	}
	return x1.lift/block < x2.lift/block;
}	

inline void add(int x) {
	res -= has[x]*has[x];
	++ has[x];
	res += has[x]*has[x];
}

inline void del(int x) {
	res -= has[x]*has[x];
	-- has[x];
	res += has[x]*has[x];
}


inline void solve(int l, int r) {
	while(R < r) {
		add(a[++ R]);
	}
	while(L > l) {
		add(a[-- L]);
	}
	while(R > r) {
		del(a[R --]);
	}
	while(L < l) {
		del(a[L ++]);
	}
}

int main(int argc, char const *argv[]) {
    ios::sync_with_stdio(false);
    cin.tie(0);     cout.tie(0);
   	int n, m, k;
   	cin >> n >> m >> k;
   	block = sqrt(n);
   	for(int i = 1; i <= n; i ++) {
   		cin >> a[i];
   	}
   	for(int i = 1; i <= m; i ++) {
   		cin >> q[i].lift >> q[i].right;
   		q[i].idx = i;
   	}
   	sort(q+1, q+1+m, cmp);

   	vector<int > ans(m+1);
   	for(int i = 1; i <= m; i++) {
   		solve(q[i].lift, q[i].right);
   		ans[q[i].idx] = res;
   	}
   	for(int i = 1; i <= m; i ++) {
   		cout << ans[i]<<  endl;
   	}
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值