P2709 小 B 的询问

莫队模板题

CODE
#include <bits/stdc++.h>
using namespace std;
using LL = long long;

const int N = 5e4 + 10, M = 510;
int n, m, k, block;
int lal = 1, lar = 0;
int bl[N], cnt[N], a[N];
LL ans[N], sum;

struct node {
	int l, r, id;
	bool operator < (const node &T) const {
		if(bl[l] == bl[T.l]) return r < T.r;
		return bl[l] < bl[T.l];
	}
}modui[N];

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

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

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	cin >> n >> m >> k; block = sqrt(n);
	for(int i = 1; i <= n; i ++ ) { cin >> a[i]; bl[i] = (i - 1) / block; } 
	for(int i = 1; i <= m; i ++ ) {
		cin >> modui[i].l >> modui[i].r; modui[i].id = i;
	}	
	
	sort(modui + 1, modui + 1 + m);
	
	for(int i = 1; i <= m; i ++ ) {
		int l = modui[i].l, r = modui[i].r;
		while(lal > l) lal --, add(a[lal]);
		while(lar < r) lar ++, add(a[lar]);
		while(lal < l) del(a[lal]), lal ++;
		while(lar > r) del(a[lar]), lar --;
		ans[modui[i].id] = sum;
	}
	
	for(int i = 1; i <= m; i ++ ) {
		cout << ans[i] << "\n";
	}
	
  return 0;
}

posted @   ccz9729  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示
主题色彩