【Luogu4396】[AHOI2013]作业(莫队)
题面
题解
模板题
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 300300
inline int read()
{
int x=0;bool t=false;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=true,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return t?-x:x;
}
const int blk=550;
struct Query{int l,r,bl,a,b,id;}p[MAX];
bool operator<(Query a,Query b){if(a.bl!=b.bl)return a.bl<b.bl;return a.r<b.r;}
int n,m,a[MAX],num[MAX],bs[MAX],bnum[MAX],o[MAX],tot,bh[MAX];
int Bound(int x){return lower_bound(&o[1],&o[tot+1],x)-o;}
int ans1[MAX],ans2[MAX],Ans;
void Add(int x)
{
if(!num[a[x]]++)++bnum[bh[a[x]]];
bs[bh[a[x]]]+=1;
}
void Del(int x)
{
if(!--num[a[x]])--bnum[bh[a[x]]];
bs[bh[a[x]]]-=1;
}
void Calc(int a,int b,int id)
{
int s1=0,s2=0;
for(int &i=a;i<=b&&bh[i]==bh[i-1];++i)s1+=num[i],s2+=(num[i]>=1);
for(int &i=b;i>=a&&bh[i]==bh[i+1];--i)s1+=num[i],s2+=(num[i]>=1);
if(a<=b)for(int i=bh[a];i<=bh[b];++i)s1+=bs[i],s2+=bnum[i];
ans1[id]=s1;ans2[id]=s2;
}
int main()
{
n=read();m=read();
for(int i=1;i<=n;++i)a[i]=read(),o[++tot]=a[i];
for(int i=1;i<=m;++i)
{
int l=read(),r=read(),a=read(),b=read();
p[i]=(Query){l,r,(l-1)/blk+1,a,b,i};
o[++tot]=a;o[++tot]=b;
}
sort(&o[1],&o[tot+1]);tot=unique(&o[1],&o[tot+1])-o-1;
for(int i=1;i<=n;++i)a[i]=Bound(a[i]);
for(int i=1;i<=m;++i)p[i].a=Bound(p[i].a),p[i].b=Bound(p[i].b);
sort(&p[1],&p[m+1]);
for(int i=1;i<=tot;++i)bh[i]=(i-1)/blk+1;
int L=1,R=0;
for(int i=1;i<=m;++i)
{
while(L<p[i].l)Del(L++);
while(L>p[i].l)Add(--L);
while(R<p[i].r)Add(++R);
while(R>p[i].r)Del(R--);
Calc(p[i].a,p[i].b,p[i].id);
}
for(int i=1;i<=m;++i)printf("%d %d
",ans1[i],ans2[i]);
return 0;
}