题目
思路
考虑分块
记
f
i
,
j
f_{i,j}
fi,j为i到j块的众数,
c
n
t
n
u
m
,
i
cnt_{num,i}
cntnum,i为到i块为止num出现的次数。
那么一开始可以
O
(
n
)
O(n)
O(n)计算f,
O
(
n
n
)
O(n\sqrt n)
O(nn)计算cnt。
接下来的询问即可分块,时间
O
(
m
n
)
O(m\sqrt n)
O(mn).
code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
using namespace std;
inline int read()
{
int ret,c,f=1;
while (((c=getchar())> '9'||c< '0')&&c!='-');
if (c=='-') f=-1,ret=0;
else ret=c-'0';
while ((c=getchar())>='0'&&c<='9') ret=ret*10+c-'0';
return ret*f;
}
int n,nn,m,a[40004],b[40004],l,r,block,len,cnt[40004][300],s[40004],f[300][300],bl[300],br[300];
bool vis[40004];
const int inf=0x7f7f7f7f;
int quantask(int l,int r)
{
int mx=-inf,ans=inf;
if (r-l<2*len)
{
for (int i=l;i<=r;i++)
{
if (vis[a[i]]==0) vis[a[i]]=1,s[a[i]]=1;
else s[a[i]]++;
}
for (int i=l;i<=r;i++)
{
if (vis[a[i]])
{
if (s[a[i]]>mx||(s[a[i]]==mx&&ans>a[i])) mx=s[a[i]],ans=a[i];
vis[a[i]]=0;
}
}
return b[ans];
}
int bll=l/len+1,blr=r/len+1,ss,d;
if (l==bl[l]) bll--;
if (r==br[r]) blr++;
ans=f[bll+1][blr-1];
mx=cnt[ans][blr-1]-cnt[ans][bll];
d=br[bll],ss=bl[blr];
for (int i=l;i<=d;i++)
{
if (vis[a[i]]==0) vis[a[i]]=1,s[a[i]]=1;
else s[a[i]]++;
}
for (int i=ss;i<=r;i++)
{
if (vis[a[i]]==0) vis[a[i]]=1,s[a[i]]=1;
else s[a[i]]++;
}
for (int i=l;i<=d;i++)
{
if (vis[a[i]])
{
if (s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll]>mx||(s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll]==mx&&ans>a[i])) mx=s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll],ans=a[i];
vis[a[i]]=0;
}
}
for (int i=ss;i<=r;i++)
{
if (vis[a[i]])
{
if (s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll]>mx||(s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll]==mx&&ans>a[i])) mx=s[a[i]]+cnt[a[i]][blr-1]-cnt[a[i]][bll],ans=a[i];
vis[a[i]]=0;
}
}
return b[ans];
}
int main()
{
n=read(),m=read(),len=sqrt(n);
for (int i=0;i<n;i++) a[i]=b[i]=read();
sort(b,b+n);
int tot=unique(b,b+n)-b;
int zz=0;
for (int i=0;i<n;i++)
{
a[i]=lower_bound(b,b+tot,a[i])-b;
if (i%len==0) br[zz]=i-1,bl[++zz]=i;
}
br[zz]=n-1;bl[zz+1]=br[zz+1]=n,block=zz;
for (int i=1;i<=block;i++)
{
for (int j=bl[i];j<n;j++) s[a[j]]=0;
int lst=bl[i],au=-inf,z=inf;
for (int j=i;j<=block;j++)
{
while (lst<=br[j])
{
s[a[lst]]++;
if (s[a[lst]]>au||(s[a[lst]]==au&&z>a[lst])) z=a[lst],au=s[a[lst]];
lst++;
}
f[i][j]=z;
}
}
memset(s,0,sizeof(s));
for (int i=1;i<=block;i++)
{
for (int j=0;j<tot;j++) cnt[j][i]=cnt[j][i-1];
for (int j=bl[i];j<=br[i];j++) cnt[a[j]][i]=++s[a[j]];
}
int lans=0;
while (m--)
{
int l=(read()+lans-1)%n,r=(read()+lans-1)%n;
if (l>r) swap(l,r);
lans=quantask(l,r);
printf("%d\n",lans);
}
return 0;
}