这题的数据结构比较多,要保存区间内最左边的数与其出现的次数,最右边的数与其出现的次数,还要保存区间出现的次数最多的值!!
刚开始题意理解错了,以为求区间出现次数最多的数!郁闷,都怪自己太心急了,写了半天,调试的时候才知道错了!
题意只要求出区间的数出现的频率的最大值,这就简单多了!!
#include<stdio.h>
#include<stdlib.h>
#define Max 100010
struct node
{
int l,r;
int lnum;//最左边的数
int rnum;//最右边的数
int count;//频率最大
int lcount;//最左边的数出现的次数
int rcount;//最右边的数出现的次数
}tree[4*Max];
int s[Max];
int count,rnum,rcount;
void build(int l,int r,int step)
{
tree[step].l=l;
tree[step].r=r;
if(tree[step].l==tree[step].r)
{
tree[step].lnum=s[l];
tree[step].rnum=s[l];
tree[step].count=1;
tree[step].rcount=1;
tree[step].lcount=1;
return ;
}
int mid=(l+r)/2;
build(l,mid,step*2);
build(mid+1,r,step*2+1);
tree[step].lnum=tree[2*step].lnum;
tree[step].rnum=tree[2*step+1].rnum;
tree[step].lcount=tree[2*step].lcount;
tree[step].rcount=tree[2*step+1].rcount;
if(tree[2*step].count>=tree[step*2+1].count)
{
tree[step].count=tree[2*step].count;
}
else
{
tree[step].count=tree[2*step+1].count;
}
if(tree[2*step].rnum==tree[2*step+1].lnum)
{
int ans=tree[2*step].rcount+tree[2*step+1].lcount;
if(ans>tree[step].count)
{
tree[step].count=ans;
}
if(tree[2*step].rnum==tree[2*step+1].rnum)
{
tree[step].rcount+=tree[step*2].rcount;
}
if(tree[2*step].lnum==tree[2*step+1].lnum)
{
tree[step].lcount+=tree[2*step+1].lcount;
}
}
}
void compute(int l,int r,int step)
{
if(tree[step].l==l&&tree[step].r==r)
{
int tmp=tree[step].rcount;
if(tree[step].count>count)
{
count=tree[step].count;
}
if(tree[step].lnum==rnum)
{
int sum=rcount+tree[step].lcount;
if(sum>count)
{
count=sum;
}
if(tree[step].rnum==rnum)
tmp=rcount+tree[step].rcount;
}
rcount=tmp;
rnum=tree[step].rnum;
return ;
}
int mid=(tree[step].l+tree[step].r)/2;
if(r<=mid)
{
compute(l,r,step*2);
}
else
{
if(mid<l)
compute(l,r,step*2+1);
else
{
compute(l,mid,step*2);
compute(mid+1,r,step*2+1);
}
}
}
int main()
{
int n,a,b,m,i;
while(scanf("%d",&n))
{
if(n==0)
break;
scanf("%d",&m);
for(i=1;i<=n;i++)
scanf("%d",&s[i]);
build(1,n,1);
while(m--)
{
scanf("%d%d",&a,&b);
if(a==b)
{
printf("1\n");
continue;
}
rcount=count=0;//初始化
rnum=9999999;//初始化
compute(a,b,1);
printf("%d\n",count);
}
}
return 0;
}