线段树维护区间众数

线段树维护区间众数,需要维护三个值,分别是:以左端点为起点的最大连续长度ls,以右端点为终点的最大连续长度rs,区间的最大连续长度ms;需要注意以下细节:

1.那么父区间的ls可以由左区间的ls向上合并得到,父区间的rs可以由右区间的rs向上合并得到。当然需要考虑左右区间为满区间的情况,如果相邻两个值相等且左右区间各自为满的情况需要考虑父区间的ls 和 rs跨到另一个区间的问题。父区间的ms可以由左区间的ms,右区间的ms,左区间的rs + 右区间的ls三者最大得到。

2.查询的时候先查出左区间最大,再查出右区间最大,最后如果相邻两个值相等的时候需要考虑跨区间的长度可能比左右区间最大还大一点。而且左区间的最大右连续的左端点比查询区间左端点还要远(端点值更小),右区间的最大左连续的右端点比查询区间右端点还要远(端点值更大)两种情况。

代码

#include<iostream>
#include<algorithm>
#include<queue>
#include<set>
#include<unordered_map>
#include<stack>
#include<cstdio>
#include<cctype>
#include<vector>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<bitset>
#define PI acos(-1)
#define ll long long
using namespace std;
typedef pair<int,int> pii;
const int N=1e5+10;
const double esp=1e-5;
const ll mod=1e9+7;

struct Tree{
    int ls; //以左端点为起点的最大连续长度
    int rs; //以右端点为终点的最大连续长度
    int ms; //区间的最大连续长度
}tr[N<<2];
int n,a[N];
void pushup(int k,int l,int r){ //向上合并区间
    int m=(l+r)>>1;
    tr[k].ls=tr[k<<1].ls;
    tr[k].rs=tr[k<<1|1].rs;
    tr[k].ms=max(tr[k<<1].ms,tr[k<<1|1].ms);
    if(a[m]==a[m+1]){ //相邻的值相等可能需要左右区间合并
        if(tr[k<<1].ms==m-l+1){
            tr[k].ls+=tr[k<<1|1].ls;
        }
        if(tr[k<<1|1].ms==r-m){
            tr[k].rs+=tr[k<<1].rs;
        }
        tr[k].ms=max(tr[k].ms,tr[k<<1].rs+tr[k<<1|1].ls);
    }
}
void build(int k,int l,int r){ //建树
    if(l==r){
        tr[k].ls=tr[k].rs=tr[k].ms=1;
        return ;
    }
    int m=l+r>>1;
    build(k<<1,l,m);
    build(k<<1|1,m+1,r);
    pushup(k,l,r);
}
int query(int k,int l,int r,int ql,int qr){ //查询
    if(qr<l||r<ql)
        return 0;
    if(ql<=l&&r<=qr){
        return tr[k].ms;
    }
    int m=l+r>>1;
    int s1=query(k<<1,l,m,ql,qr);
    int s2=query(k<<1|1,m+1,r,ql,qr);
    int res=max(s1,s2);
    if(a[m]==a[m+1]){
        res=max(res,min(tr[k<<1].rs,m-ql+1)+min(tr[k<<1|1].ls,qr-m));
    }
    return res;
}
int main()
{
    int n,q;
    while(~scanf("%d",&n)&&n){
        scanf("%d",&q);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        build(1,1,n);
        while(q--){
            int x,y;
            scanf("%d%d",&x,&y);
            int ans=query(1,1,n,x,y);
            printf("%d\n",ans);
        }
    }
    return 0;
}


以上代码为此题的答案:HDU1806.Frequent values

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值