BZOJ 1878 SDOI2009 HH的項鍊 樹狀數組/莫隊算法

題目大意:給定一個序列。求一個區間內有多少個不一樣的數ios

正解是樹狀數組 將所有區間依照左端點排序 而後每次僅僅統計左端點開始的每種顏色的第一個數便可了 用樹狀數組維護算法

我寫的是莫隊算法 莫隊明顯能搞 m√m明顯慢了點但是仍是能接受的一個複雜度數組

一開始離散化數組開小了各類秒RE…… 跪了post

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 50500
using namespace std;
struct abcd{
	int l,r,pos;
	bool operator < (const abcd &x) const;
}q[200200];
int n,m,block,l=1,r=0,now,a[M],map[1001001],tot;
int cnt[M],ans[200200];
bool abcd :: operator < (const abcd &x) const
{
	if( (l-1)/block == (x.l-1)/block )
		return r < x.r ;
	return (l-1)/block < (x.l-1)/block ;
}
inline void Update(int x)
{
	cnt[x]++;
	if(cnt[x]==1)
		++now;
}
inline void Downdate(int x)
{
	cnt[x]--;
	if( !cnt[x] )
		--now;
}
int main()
{
	int i,x;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		scanf("%d",&x);
		if(!map[x]) map[x]=++tot;
		a[i]=map[x];
	}
	cin>>m;
	for(i=1;i<=m;i++)
		scanf("%d%d",&q[i].l,&q[i].r),q[i].pos=i;
	block=static_cast<int>(sqrt(n)+1e-7);
	sort(q+1,q+m+1);
	for(i=1;i<=m;i++)
	{
		while(r<q[i].r)
			Update(a[++r]);
		while(l>q[i].l)
			Update(a[--l]);
		while(r>q[i].r)
			Downdate(a[r--]);
		while(l<q[i].l)
			Downdate(a[l++]);
		ans[q[i].pos]=now;
	}
	for(i=1;i<=m;i++)
		printf("%d\n",ans[i]);
}
相關文章
相關標籤/搜索