统计不同点—中上—1878: [SDOI2009]HH的项链

http://www.zybbs.org/JudgeOnline/problem.php?id=1878

树状数组+离线算法

因为不需要在线更新结点所以想到离线算法速度更快

难点在于相同颜色的算一个,所以要灵活运用树状数组

用next记录每个点后面的第一个颜色相同的点

按左区间排序

i:1->n

不断更新updata(next[i])

到了其中一个的左区间就更新

最后还原排序下

View Code
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;

int n,q,c[50001];

int lowbit(int x)
{
return x&(-x);
}

void updata(int x)
{
int i;
for(i=x;i<=n;i+=lowbit(i))
++c[i];
}

int getsum(int x)
{
int i,temp=0;
for(i=x;i>=1;i-=lowbit(i))
temp+=c[i];

return temp;
}

struct data
{
int ll,rr;
int no;
int all;
}s[200001];

int a[50001],first[1000001],next[50001];

int cmp1(data a,data b)
{
return a.ll<b.ll;
}

int cmp2(data a,data b)
{
return a.no<b.no;
}

int main()
{
scanf("%d",&n);
int i,j;
for(i=1;i<=n;++i)//ͳ¼Æ¸üв»Í¬µÄ¸öÊý
{
scanf("%d",&a[i]);
if(first[a[i]]==0)
{
updata(i);
}
first[a[i]]=i;
}

memset(first,0,sizeof(first));
for(i=n;i>=1;--i)//ºóÍùÇ°¸üеõ½next
{

if(first[a[i]])next[i]=first[a[i]];
first[a[i]]=i;
}

scanf("%d",&q);
for(i=1;i<=q;++i)
{
scanf("%d%d",&s[i].ll,&s[i].rr);
s[i].no=i;
}
sort(&s[1],&s[q+1],cmp1);

int k;
for(i=1,k=0;i<=q;++i)
{
for(j=k+1;j<s[i].ll;++j)
{
if(next[j])updata(next[j]);
}
k=s[i].ll-1;

s[i].all=getsum(s[i].rr)-getsum(k);
}

sort(&s[1],&s[q+1],cmp2);

for(i=1;i<=q;++i)
{
printf("%d\n",s[i].all);
}

return 0;
}



原文地址:https://www.cnblogs.com/huhuuu/p/2255626.html