Curious Cupid
There are K different languages in the world. Each person speaks one and only one language. There are exactly N single men and N
single women.
Cupid, the god of love, wants to match every single man to a single woman, and vice versa. Everybody wants to find a partner who speaks the same language as s/he does. Communication between the couple is very important! Cupid asks these N
men to stand in a line, and likewise for the N women. Cupid knows that the ith man speaks language ai and the ith woman speaks language bi
.
It is too hard for Cupid to match all people at the same time. What Cupid does is to repeatedly look at some specific interval in these two lines, pick the men and women in that interval and find the maximum number of man-woman pairs who speak the same language and can be matched.
Input
-
The first line contains three integers N
, M and K (1≤N≤50000,1≤M≤50000,1≤K≤1000000)
-
.
-
The second line contains N
integers a0,a1,a2,…,aN−1, where ai (0≤ai<K) is the language spoken by the i
-
th man.
-
The third line contains N
integers b0,b1,b2,…,bN−1, where bi (0≤bi<K) is the language spoken by the i
-
th woman.
-
In the next M
lines, each line contains two integers L and R (0≤L≤R<N), representing the starting and ending index of the interval. That is, Cupid is looking at men L,L+1,…,R and women L,L+1,…,R
-
.
Output
For each interval, print the maximum number of couples Cupid could match.
Sample Input 1 | Sample Output 1 |
---|---|
3 4 2 0 0 1 0 0 0 0 0 2 2 0 1 1 2 |
1 0 2 1 |
分析:莫队算法的应用;
代码:
#include <bits/stdc++.h> using namespace std; const int maxn=1e6+10; int n,m,k,t,cnta[maxn],cntb[maxn],a[maxn],b[maxn],bel[maxn],tot,cnt,ans[maxn]; long long ret; struct node { int l,r,id,block; bool operator<(const node&p)const { return block==p.block?r<p.r:block<p.block; } }qu[maxn]; int main() { int i,j; scanf("%d%d%d",&n,&m,&k); int sz=(int)sqrt(n); for(i=1;i<=n;i++) { bel[i]=tot; if(++cnt==sz)tot++,cnt=0; } for(i=1;i<=n;i++)scanf("%d",&a[i]); for(i=1;i<=n;i++)scanf("%d",&b[i]); for(i=1;i<=m;i++)scanf("%d%d",&qu[i].l,&qu[i].r),qu[i].l++,qu[i].r++,qu[i].id=i,qu[i].block=bel[qu[i].l]; sort(qu+1,qu+m+1); int l=1,r=0; for(i=1;i<=m;i++) { while(r < qu[i].r) { ++cnta[a[++r]]; if(cntb[a[r]]>=cnta[a[r]])++ret; ++cntb[b[r]]; if(cnta[b[r]]>=cntb[b[r]])++ret; } while(l > qu[i].l) { ++cnta[a[--l]]; if(cntb[a[l]]>=cnta[a[l]])++ret; ++cntb[b[l]]; if(cnta[b[l]]>=cntb[b[l]])++ret; } while(r > qu[i].r) { if(cntb[a[r]]>=cnta[a[r]])--ret; --cnta[a[r]]; if(cnta[b[r]]>=cntb[b[r]])--ret; --cntb[b[r--]]; } while(l < qu[i].l) { if(cntb[a[l]]>=cnta[a[l]])--ret; --cnta[a[l]]; if(cnta[b[l]]>=cntb[b[l]])--ret; --cntb[b[l++]]; } ans[qu[i].id]=ret; } for(i=1;i<=m;i++)printf("%d\n",ans[i]); return 0; }