You are given an array with n integers a1, a2, ..., an, and q queries to answer.
Each query consists of four integers l1,r1,l2 andr2. Your task is to count the number of pairs of indices(i, j) satisfying the following conditions:
- ai = aj
- l1 ≤ i ≤ r1
- l2 ≤ j ≤ r2
The first line of the input contains an integer n (1 ≤ n ≤ 50 000) — the size of the given array.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
The third line contains an integer q (1 ≤ q ≤ 50 000) — the number of queries.
Each of the next q lines contains four integersl1,r1,l2,r2 (1 ≤ l1 ≤ r1 ≤ n,1 ≤ l2 ≤ r2 ≤ n), describing one query.
For each query count the number of sought pairs of indices (i, j) and print it in a separate line.
7 1 5 2 1 7 2 2 8 1 3 4 5 2 3 5 7 1 4 3 7 2 6 4 7 1 6 2 5 3 3 6 7 4 5 1 4 2 3 4 5
1 2 5 6 6 2 2 0
之前在知乎上莫队有推荐一个讲解莫队算法的题解,题目是小z的袜子。和这道题基本类似。http://blog.youkuaiyun.com/bossup/article/details/39236275
区别在于,那道题求得是单个区间内相同数字的对数,而这道题在于求解两个不同区间对应的相同数字的对数。
所以怎么做呢?我们用f(i,j)表示区间[i,j]内相同数字的对数。
把整个区间想象成一个正方形,正方形的行和列都是从1到n个数。每一点代表了一对数的序偶。
我们要求解的答案是从[l1,r1]和[l2,r2]中分别选出一个数。在正方形中代表了一个矩形。而我们能用莫队求出的f[i,j]代表其中的一个子正方形。由此便可以求出查询结果。具体看代码。
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
typedef long long LL;
const int MAXN = 200000+10;
struct q{
int l,r,id,k;
};
q qu[MAXN];
int a[MAXN];
LL ans[MAXN]={0};
LL num[MAXN]={0};
int pos[MAXN];
int n;
LL res;
int cmp(q a,q b){
if(pos[a.l]==pos[b.l])
return a.r<b.r;
else
return pos[a.l]<pos[b.l];
}
void update(int x,int d){
if(d==1){
res+=num[a[x]];
num[a[x]]+=1;
}
if(d==-1){
res-=(num[a[x]]-1);
num[a[x]]-=1;
}
}
int main(){
// freopen("in.txt","r",stdin);
scanf("%d",&n);
int bk=ceil(sqrt(n));
for(int i=1;i<=n;i++){
scanf("%d",a+i);
pos[i]=(i-1)/bk;
}
int m;
scanf("%d",&m);
int tot=0;
for(int i=0;i<m;i++){
int l1,r1,l2,r2;
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
qu[tot].l=l1,qu[tot].r=r2,qu[tot].k=1,qu[tot++].id=i;
qu[tot].l=l1,qu[tot].r=l2-1,qu[tot].k=-1,qu[tot++].id=i;
qu[tot].l=r1+1,qu[tot].r=r2,qu[tot].k=-1,qu[tot++].id=i;
qu[tot].l=r1+1,qu[tot].r=l2-1,qu[tot].k=1,qu[tot++].id=i;
}
int l=1,r=0;
sort(qu,qu+tot,cmp);
for(int i=0;i<tot;i++){
if(r<qu[i].r){
for(int j=r+1;j<=qu[i].r;j++)
update(j,1);
}
else if(r>qu[i].r){
for(int j=r;j>=qu[i].r+1;j--)
update(j,-1);
}
r=qu[i].r;
if(l<qu[i].l){
for(int j=l;j<=qu[i].l-1;j++)
update(j,-1);
}
else if(l>qu[i].l){
for(int j=l-1;j>=qu[i].l;j--)
update(j,1);
}
l=qu[i].l;
ans[qu[i].id]+=res*qu[i].k;
//printf("[[[[[%d %d %d\n",l,r,res);
}
for(int i=0;i<m;i++){
printf("%lld\n",ans[i]);
}
}