luogu P4135 作诗

背景:

杠了两天。
卡常。
不开 O 2 O_2 只有 10 P t s 10Pts
我的时间复杂度是: Θ ( n l o g n n ) \Theta(nlogn\sqrt{n})
然而发现跑 R a n k 1 Rank 1 的时间复杂度是: Θ ( n n ) \Theta(n\sqrt{n})
我惊了(我太菜)。

题目传送门:

https://www.luogu.org/problemnew/show/P4135

题意:

n n 个数,每一次询问 L , R L,R 区间的出现偶数次的正整数的次数。
强制在线。(不然就是莫队的水题了)。

思路:

只能分块了。
毒瘤出题人。
考虑预处理。

f [ i ] [ j ] f[i][j] 表示第 i i 块到第 j j 块的答案。
可以预处理出来( Θ ( n n ) \Theta(n\sqrt{n}) )。

于是对于一个询问的区间,不妨分为三个部分:两个小块和中间完整的大块。
对于那一个大块,我们可以 Θ ( 1 ) \Theta(1) 出解。
有人会问:两个小块也会影响答案啊,中间求出来的有什么用吗?
考虑做两个小块的时间复杂度是 Θ ( n ) \Theta(\sqrt{n}) ,在做的时候,不妨让其与中间的那一块联合求解,因为你可以在处理出每一个值所有的位置,再带上一个二分,就可以知道在当前这一块内的个数。再像预处理一般求解即可。

细节较多,可以认真思考。

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
vector<int> list[100010];
queue<int> F;
	int n,m,q,block;
	int a[100010],tot[100010];
	int belong[100010],l[10010],r[10010],f[500][500];//第i块到第j块的答案
void init()
{
	for(int i=1;i<=belong[n];i++)
	{
		int tmp=0;
		for(int j=l[i];j<=n;j++)
		{
			tot[a[j]]++;
			if((tot[a[j]]&1)&&tot[a[j]]!=1) tmp--;
			if(!(tot[a[j]]&1)) tmp++;
			f[i][belong[j]]=tmp;
		}
		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 solve(int x,int y)
{
	int ans=0;
	while(!F.empty()) F.pop();
	if(belong[x]==belong[y])
	{
		for(int i=x;i<=y;i++)
		{
			if(!tot[a[i]]) F.push(a[i]);
			tot[a[i]]++;
		}
		while(!F.empty())
		{
			if(!(tot[F.front()]&1)) ans++;
			tot[F.front()]=0;
			F.pop();
		}
	}
	else
	{
		ans=f[belong[x]+1][belong[y]-1];
		for(int i=x;i<=r[belong[x]];i++)
		{
			if(!tot[a[i]]) F.push(a[i]);
			tot[a[i]]++;
		}
		for(int i=y;i>=l[belong[y]];i--)
		{
			if(!tot[a[i]]) F.push(a[i]);
			tot[a[i]]++;
		}
		while(!F.empty())
		{
			int now=F.front();
			F.pop();
			int sum=calc(x,y,now),sum1=sum-tot[now],sum2=tot[now];
			if(sum1&1) ans+=(sum2&1);
			else if(sum1) ans-=(sum2&1);
			else ans+=((sum2&1)^1);
		}
		for(int i=x;i<=r[belong[x]];i++)
			tot[a[i]]=0;
		for(int i=y;i>=l[belong[y]];i--)
			tot[a[i]]=0;
	}
	return ans;
}
int main()
{
	int x,y;
	scanf("%d %d %d",&n,&m,&q);
	block=sqrt(n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		list[a[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)%n+1,y=(y+last)%n+1;
		if(x>y) swap(x,y);
		printf("%d\n",last=solve(x,y));
	}
}

猜你喜欢

转载自blog.csdn.net/zsyz_ZZY/article/details/85260864
今日推荐