hdu 1540 线段树 点所在的区间最大连续长度

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string.h>
#include <queue>                   //hdu 1540   线段树
#define N 50005                 //单点更新,求一个点所在区间的最大连续长度
using namespace std;
int a[N];        //数组a的操作相当于栈
struct tree
{
    int left, right;
    int lmax, rmax, max1;     //lmax从左边开始连续的最大长度, rmax从右边开始最大的连续长度, max1最大长度
}p[N*4];

void build(int l, int r, int n)
{
    p[n].left=l;
    p[n].right=r;
    p[n].lmax=p[n].rmax=p[n].max1=r-l+1;
    if(l==r)
        return ;
    int mid=(l+r)>>1;
    build(l, mid, n<<1);
    build(mid+1, r, (n<<1)|1);
    return ;
}
void update(int k, int n, int g)       //g为0表示破坏, g为1表示维修
{
    if(p[n].left==p[n].right)
    {
        if(g)
        {
            p[n].lmax=p[n].rmax=p[n].max1=1;
        }
        else p[n].lmax=p[n].rmax=p[n].max1=0;
        return ;
    }
    int mid=(p[n].left+p[n].right)>>1;
    if(k<=mid)                         
        update(k, n<<1, g);
    else update(k, (n<<1)|1, g);
    p[n].lmax=p[n<<1].lmax;        //前面的操作已经递归到叶节点了,这里先让p[n].lmax=p[n<<1].lmax,后面再作判断中间是否有断开
    p[n].rmax=p[(n<<1)|1].rmax;
    p[n].max1=max(p[n].lmax, p[n].rmax);
    p[n].max1=max(p[n].max1, p[n<<1].rmax+p[(n<<1)|1].lmax);
    if(p[n<<1].right-p[n<<1].left+1==p[n<<1].lmax)   //判断p[n]中间是否有断开,没断开则连上
        p[n].lmax+=p[(n<<1)|1].lmax;
    if(p[(n<<1)|1].right-p[(n<<1)|1].left+1==p[(n<<1)|1].rmax)
        p[n].rmax+=p[n<<1].rmax;
    return ;
}
int f(int k, int n)
{
    int s;
    if(p[n].left==p[n].right||p[n].max1==0||p[n].right-p[n].left+1==p[n].max1)
    {
        return p[n].max1;
    }
    int mid=(p[n].left+p[n].right)>>1;
    if(k<=mid)
    {
        if(k>p[n<<1].right-p[n<<1].rmax)   //判断是否在p[n<<1]的右连续里,如果是的话则在加上mid+1的连续段
            s=f(k, n<<1)+p[(n<<1)|1].lmax;
        else s=f(k, n<<1);
    }
    else 
    {
        if(k<p[(n<<1)|1].left+p[(n<<1)|1].lmax)
            s=p[n<<1].rmax+f(k, (n<<1)|1);
        else s=f(k, (n<<1)|1);
    }
    return s;
}

int main()
{
    int n, m, j, h;
    char c[3];
    while(scanf("%d%d", &n, &m)!=EOF)
    {
        build(1, n, 1);
        j=0;
        while(m--)
        {
            scanf("%s", c);
            if(c[0]=='D')
            {
                scanf("%d", &h);
                a[j++]=h;
                update(h, 1, 0);
            }
            if(c[0]=='R')
            {
                h=a[--j];
                update(h, 1, 1);
            }
            if(c[0]=='Q')
            {
                scanf("%d", &h);
                printf("%d\n", f(h, 1));
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值