https://blog.csdn.net/weixin_30337251/article/details/99742674 参考文章
#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define N 50005
using namespace std;
struct node {
int l, r, id, belong, k;
} q[N << 2];
int Dl[N], Dr[N], a[N];
ll res, ans[N];
int n, m, tot, belong;
bool cmp(node A, node B) {
if(A.belong == B.belong)
return A.r < B.r;
return A.belong < B.belong;
}
void AddL(int x) {
res += Dr[a[x]];
++ Dl[a[x]];
}
void AddR(int x) {
res += Dl[a[x]];
++ Dr[a[x]];
}
void DecL(int x) {
res -= Dr[a[x]];
-- Dl[a[x]];
}
void DecR(int x) {
res -= Dl[a[x]];
-- Dr[a[x]];
}
int main() {
cin>>n;
belong = sqrt(n);
for (int i = 1; i <= n; i ++)
cin>>a[i];
cin>>m;
tot = 0;
for (int i = 1; i <= m; i ++) {
int l1, r1, l2, r2;
cin>>l1>>r1>>l2>>r2;
q[++ tot] = {l1 - 1, l2 - 1, i, (l1 - 2) / belong + 1, 1};
q[++ tot] = {r1, r2, i, (r1 - 1) / belong + 1, 1};
q[++ tot] = {l1 - 1, r2, i, (l1 - 2) / belong + 1, -1};
q[++ tot] = {r1, l2 - 1, i, (r1 - 1) / belong + 1, -1};
}
sort(q + 1, q + 1 + tot, cmp);
int l = 0, r = 0;
for (int i = 1; i <= tot; i ++) {
while (r < q[i].r)
AddR(++ r);
while (l > q[i].l)
DecL(l --);
while (r > q[i].r)
DecR(r --);
while (l < q[i].l)
AddL(++ l);
ans[q[i].id] += q[i].k * res;
}
for (int i = 1; i <= m; i ++)
cout<<ans[i]<<endl;
return 0;
}