luogu P4168 [Violet]蒲公英

背景:

又是一道强制在线的分块题。

题目传送门:

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));
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值