莫队

莫队有一种暴力的美感,它只是通过分块降低了暴力做法的复杂度

#include<bits/stdc++.h>
using namespace std;
const int N = 5e4 + 5;
long long ans, out[N], n, m, k, a[N], b[N], tong[N];
void add(int x){
	ans += 2ll * tong[x] + 1;
	tong[x]++;
}
void sub(int x){
	ans -= 2ll * tong[x] - 1;
	tong[x]--;
}
struct cx{
	int l, r, bh;
}c[N];
bool cmp(cx x, cx y){
	if(b[x.l] == b[y.l]) return x.r < y.r;
	else return b[x.l] < b[y.l];
}
int main(){
	cin >> n >> m >> k;	
	int g = sqrt(n);
	for(int i = 1; i <= n; i++){
		cin >> a[i];
		b[i] = i / g;
	}
	for(int i = 1; i <= m; i++){
		cin >> c[i].l >> c[i].r;
		c[i].bh = i;
	}
	sort(c + 1, c + m + 1, cmp);
	int nwl, nwr, ltl = 1, ltr = 0; 
	for(int i = 1; i <= m; i++){
		nwl = c[i].l; nwr = c[i].r;
		while(ltl > nwl) ltl--, add(a[ltl]);
		while(ltr < nwr) ltr++, add(a[ltr]);
		while(ltl < nwl) sub(a[ltl]), ltl++;
		while(ltr > nwr) sub(a[ltr]), ltr--;
		out[c[i].bh] = ans;
	}
	for(int i = 1; i <= m; i++){
		cout << out[i] << endl;
	}
	return 0;
}
posted @ 2025-11-22 15:58  Turkey_VII  阅读(3)  评论(0)    收藏  举报