背景:
又是一道强制在线的分块题。
题目传送门:
https://www.luogu.org/problemnew/show/P4168
题意:
n
n
n个数,每次询问
[
L
,
R
]
[L,R]
[L,R]区间内的众数。
强制在线。(不然就是莫队水题了)。
思路:
同luogu P4135 作诗。
就不再写了。
时间复杂度:
Θ
(
n
l
o
g
n
n
)
\Theta(nlogn\sqrt{n})
Θ(nlognn)。
正解时间复杂度:
Θ
(
n
n
)
\Theta(n\sqrt{n})
Θ(nn)
正解在此。(顶礼膜拜)。
代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> list[100010];
map<int,int> F;
int n,q,block,t=0;
int a[100010],tot[100010];
int id[100010],belong[100010],l[10010],r[10010],f[500][500];//第i块到第j块的答案
void init()
{
for(int i=1;i<=belong[n];i++)
{
int ma=0,now=2147483647;
for(int j=l[i];j<=n;j++)
{
if(ma==tot[id[j]]) now=a[j];
tot[id[j]]++;
ma=max(ma,tot[id[j]]);
if(ma==tot[id[j]]) now=min(now,a[j]);
f[i][belong[j]]=now;
}
memset(tot,0,sizeof(tot));
}
}
int calc(int x,int y,int ID)
{
return upper_bound(list[ID].begin(),list[ID].end(),y)-lower_bound(list[ID].begin(),list[ID].end(),x);
}
int ma,ans;
void work(int x,int y,int now)
{
int sum=calc(x,y,id[now]);
if(sum>ma) ma=sum,ans=a[now];
else if(sum==ma) ans=min(ans,a[now]);
}
int solve(int x,int y)
{
ma=0,ans=2147483647;
if(belong[x]==belong[y])
{
for(int i=x;i<=y;i++)
{
if(ma==tot[id[i]]) ans=a[i];
tot[id[i]]++;
ma=max(ma,tot[id[i]]);
if(ma==tot[id[i]]) ans=min(ans,a[i]);
}
for(int i=x;i<=y;i++)
tot[id[i]]=0;
}
else
{
ans=f[belong[x]+1][belong[y]-1];
ma=calc(x,y,F[ans]);
for(int i=x;i<=r[belong[x]];i++)
{
if(!tot[id[i]]) work(x,y,i);
tot[id[i]]++;
}
for(int i=y;i>=l[belong[y]];i--)
{
if(!tot[id[i]]) work(x,y,i);
tot[id[i]]++;
}
for(int i=x;i<=r[belong[x]];i++)
tot[id[i]]=0;
for(int i=y;i>=l[belong[y]];i--)
tot[id[i]]=0;
}
return ans;
}
int main()
{
int x,y;
scanf("%d %d",&n,&q);
block=sqrt(n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(!F[a[i]]) F[a[i]]=++t;
id[i]=F[a[i]];
list[id[i]].push_back(i);
belong[i]=i/block+1;
if(belong[i]!=belong[i-1]) l[belong[i]]=i,r[belong[i-1]]=i-1;
}
r[belong[n]]=n;
init();
int last=0;
for(int i=1;i<=q;i++)
{
scanf("%d %d",&x,&y);
x=(x+last-1)%n+1,y=(y+last-1)%n+1;
if(x>y) swap(x,y);
printf("%d\n",last=solve(x,y));
}
}