BZOJ1878:[SDOI2009]HH的项链

浅谈树状数组与线段树:https://www.cnblogs.com/AKMer/p/9946944.html

题目传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=1878

用线段树的话显然在线肯定是做不了的……这个倒是让我想起来某flag……

我们考虑将询问离线,对于每一个[\(l,r\)],我们都将其存在\(r\)这个位置上。我们令区间[\(l,r\)]中相同编号的贝壳只有最右边的那一个为\(1\),其余的都为\(0\),这样区间和就是贝壳种类数了。我们直接在原数列上从左往右扫,对于每一个位置,我们都将上一个与它相同的贝壳位置上的\(1\)变成\(0\),然后把当前位置变成\(1\),这样就保证了“最右性”,由于\(r\)固定,所以直接询问就行了。

时间复杂度:\(O(nlogn)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
#define low(i) ((i)&(-i))

const int maxn=5e4+5,maxm=2e5+5;

int n,m,tot;
int now[maxn],pre[maxm],son[maxm];
int a[maxn],ans[maxm],tmp[maxn],lst[maxn];

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

void add(int a,int b) {
	pre[++tot]=now[a];
	now[a]=tot;son[tot]=b;
}

struct TreeArray {
	int c[maxn];

	void add(int pos,int v) {
		for(int i=pos;i<=n;i+=low(i))
			c[i]+=v;
	}

	int query(int pos) {
		int res=0;
		for(int i=pos;i;i-=low(i))
			res+=c[i];
		return res;
	}
}T;

int main() {
	n=read();
	for(int i=1;i<=n;i++)
		tmp[i]=a[i]=read(),lst[i]=n+1;//初始值为0树状数组会卡死
	sort(tmp+1,tmp+n+1);m=read();
	int cnt=unique(tmp+1,tmp+n+1)-tmp-1;
	for(int i=1;i<=n;i++)
		a[i]=lower_bound(tmp+1,tmp+cnt+1,a[i])-tmp;//离散化
	for(int i=1;i<=m;i++) {
		int l=read(),r=read();
		add(r,l);//存询问
	}
	for(int i=1;i<=n;i++) {
		T.add(lst[a[i]],-1);
		T.add(i,1);lst[a[i]]=i;//改值
		for(int p=now[i],v=son[p];p;p=pre[p],v=son[p])
			ans[p]=T.query(i)-T.query(v-1);//直接询问
	}
	for(int i=1;i<=m;i++)
		printf("%d\n",ans[i]);//离线输出
	return 0;
}

posted @ 2018-11-12 16:48  AKMer  阅读(127)  评论(0编辑  收藏  举报