1. 程式人生 > >luogu P4135 作詩

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));
	}
}