BZOJ 2821--作诗(分块)

2821: 作诗(Poetize)

Time Limit: 50 Sec  Memory Limit: 128 MB
Submit: 3263  Solved: 949
[Submit][Status][Discuss]

Description

神犇SJY虐完HEOI之后给傻×LYD出了一题:SHY是T国的公主,平时的一大爱好是作诗。由于时间紧迫,SHY作完诗之后还要虐OI,于是SHY找来一篇长度为N的文章,阅读M次,每次只阅读其中连续的一段[l,r],从这一段中选出一 些汉字构成诗。因为SHY喜欢对偶,所以SHY规定最后选出的每个汉字都必须在[l,r]里出现了正偶数次。而且SHY认 为选出的汉字的种类数(两个一样的汉字称为同一种)越多越好(为了拿到更多的素材!)。于是SHY请LYD安排选 法。LYD这种傻×当然不会了,于是向你请教……问题简述:N个数,M组询问,每次问[l,r]中有多少个数出现正偶数次。

Input

输入第一行三个整数n、c以及m。表示文章字数、汉字的种类数、要选择M次。第二行有n个整数,每个数Ai在[1, c]间,代表一个编码为Ai的汉字。接下来m行每行两个整数l和r,设上一个询问的答案为ans(第一个询问时ans=0),令L=(l+ans)mod n+1, R=(r+ans)mod n+1,若L>R,交换L和R,则本次询问为[L,R]。

Output

输出共m行,每行一个整数,第i个数表示SHY第i次能选出的汉字的最多种类数。

Sample Input

5 3 5
1 2 2 3 1
0 4
1 2
2 2
2 3
3 5

Sample Output

2
0
0
0
1

HINT

对于100%的数据,1<=n,c,m<=10^5

题目链接:

    http://www.lydsy.com/JudgeOnline/problem.php?id=2821 

Solution

    很类似区间众数的做法。。。所以就是分块啦。。。

    先预处理出第 i 块到第 j 块的答案,

    对于每次查询,只用考虑左右两块中的元素对当前答案的影响即可。。

    注意:本题块的最优大小为sqrt( n/log2(n) )

代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#define N 100050
#define LL long long
using namespace std;
inline int Read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int n,Q,C,e,m,x=0;
int a[N],g[N],sum[N],f[1500][1500],vis[N];
vector<int> q[N];
void reset(int k){
	int s=0;
	for(int i=1;i<=C;i++) sum[i]=0;
	for(int i=(k-1)*e+1;i<=n;i++) {
		sum[a[i]]++;
		if(sum[a[i]]&1) s-=(sum[a[i]]>1);
		else s++;
		f[k][g[i]]=s;
	}
}
int calc(int h,int c){
	int l=0,r=q[c].size()-1,mid;
	if(q[c][l]>h) return 0;if(q[c][r]<=h) return q[c].size();
	while(l!=r){
		mid=(l+r+1)>>1;
		if(q[c][mid]<=h) l=mid;
		else r=mid-1;
	}
	return l+1;
}
void solve(int l,int r,int K){
	int now;
	x=0;
	if(g[l]>=g[r]-1){
		for(int i=l;i<=r;i++){
			if(vis[a[i]]==K) continue;vis[a[i]]=K;
			now=calc(r,a[i])-calc(l-1,a[i]);
			if(!(now&1)) x++;
		}
		printf("%d
",x);
		return;
	}
	x=f[g[l]+1][g[r]-1];
	for(int i=l;i<=e*g[l];i++) {
		if(vis[a[i]]==K) continue;vis[a[i]]=K;
		now=calc((g[r]-1)*e,a[i])-calc(g[l]*e,a[i]);
		if((!(now&1)) && now>0) x--;
		now=calc(r,a[i])-calc(l-1,a[i]);
		if(!(now&1)) x++;
	}
	for(int i=(g[r]-1)*e+1;i<=r;i++) {
		if(vis[a[i]]==K) continue;vis[a[i]]=K;
		now=calc((g[r]-1)*e,a[i])-calc(g[l]*e,a[i]);
		if((!(now&1)) && now>0) x--;
		now=calc(r,a[i])-calc(l-1,a[i]);
		if(!(now&1)) x++;
	}
	printf("%d
",x);
	return;
}
int main(){
	char ch;
	int l,r;
	n=Read();C=Read();Q=Read();e=sqrt((double)n/log((double)n)*log(2));
	for(int i=1;i<=n;i++) {
		a[i]=Read();
		q[a[i]].push_back(i);
		g[i]=(i+e-1)/e;
	}
	m=g[n];
	for(int i=1;i<=m;i++) reset(i);
	for(int i=1;i<=Q;i++){
		l=(Read()+x)%n+1;r=(Read()+x)%n+1;
		if(l>r) swap(l,r);
		solve(l,r,i);
	}
	return 0;
}

  

  

This passage is made by Iscream-2001.

原文地址:https://www.cnblogs.com/Yuigahama/p/8080874.html