将式子拆分成四个查询,注意下标会访问到0,而且当
#include <bits/stdc++.h>
/*
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
*/
using namespace std;
const double eps = 1e-10;
const double pi = 3.1415926535897932384626433832795;
const double eln = 2.718281828459045235360287471352;
#define f(i, a, b) for (int i = a; i <= b; i++)
#define scan(x) scanf("%d", &x)
#define mp make_pair
#define pb push_back
#define lowbit(x) (x&(-x))
#define fi first
#define se second
#define SZ(x) int((x).size())
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define summ(a) (accumulate(all(a), 0ll))
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;
using ll=long long;
using a4=array<int,4>;
ll n,q,a[(int)5e4+9],cnt[2][(int)5e4+9],res,ans[(int)5e4+9],belong[(int)5e4+9],fk,l,r;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=1;i<=n;++i)cin>>a[i];
vector<a4>v;
cin>>q;
for(int i=1,x,y,z,w;i<=q;++i){
cin>>x>>y>>z>>w;
v.push_back({min(w,y),max(w,y),i,1});
v.push_back({min(x-1,z-1),max(x-1,z-1),i,1});
v.push_back({min(x-1,w),max(x-1,w),i,-1});
v.push_back({min(z-1,y),max(z-1,y),i,-1});
}
fk=ceil(n/sqrt(4.0*q));
for(int i=1;i<=n;++i)belong[i]=(i-1)/fk+1;
sort(all(v),[](const a4& aa,const a4& bb){return belong[aa[0]]==belong[bb[0]]?(belong[aa[0]]&1)^(aa[1]>bb[1]):belong[aa[0]]<belong[bb[0]];});
for(auto &&[aa,bb,cc,dd]:v){
while(l>aa)cnt[0][a[l]]-=1,res-=cnt[1][a[l]],l-=1;
while(r<bb)cnt[1][a[++r]]+=1,res+=cnt[0][a[r]];
while(l<aa)cnt[0][a[++l]]+=1,res+=cnt[1][a[l]];
while(r>bb)cnt[1][a[r]]-=1,res-=cnt[0][a[r]],r-=1;
ans[cc]+=1ll*dd*res;
}
for(int i=1;i<=q;++i)cout<<ans[i]<<"\n";
return 0;
}