PKU2892(Tunnel Warfare)线段树求最大连续区间

本文介绍了一种使用线段树求解最长连续区间的算法。针对一条直线上顶点的操作,包括破坏、查询最长连续点数及修复,通过维护左、右连续长度和最大连续长度来更新线段树,实现高效查询。
/**************************************
题目大意:
一条直线上的有n个顶点;
(1)D x 破坏顶点x;
(2)Q x 表示查询以x所在的最长的连续的点的个数,包括顶点x本身;
(3)R   修复上一次被破坏的点;
算法思想:
线段树,求最大连续区间,操作类似于pku3667;
ls 记录区间左端点开始的最大连续个数,
rs 记录区间右端点开始的最大的连续个数,
ms 表示该区间最大的连续点的个数。
***************************************/
#include<iostream>
#include<algorithm>
#include<stack>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;

#define L l,m,u<<1
#define R m+1,r,u<<1|1

const int N=50050;
int st[N];//模拟栈序列
int top;//模拟栈顶元素

struct Node
{
    int l,r;
    int ls,rs,ms;//ls:左边开始连续的最大长度;rs:右边开始最大的连续长度;ms:这个区间最大连续长度;
} T[N*3];

void build(int l,int r,int u)
{
    T[u].l=l;
    T[u].r=r;
    T[u].ls=T[u].rs=T[u].ms=r-l+1;
    if(l==r)
        return;
    int m=(l+r)>>1;
    build(L);
    build(R);
}

void update(int u,int t,int x)
{
    if(T[u].l==T[u].r)
    {
        if(x==1)
            T[u].ls=T[u].rs=T[u].ms=1;
        else
            T[u].ls=T[u].rs=T[u].ms=0;
        return;
    }
    int m=(T[u].l+T[u].r)>>1;
    if(t<=m)
        update(u<<1,t,x);
    else
        update(u<<1|1,t,x);

    T[u].ls=T[u<<1].ls;
    T[u].rs=T[u<<1|1].rs;
    T[u].ms=max(T[u<<1].ms,T[u<<1|1].ms);
    T[u].ms=max(T[u].ms,T[u<<1].rs+T[u<<1|1].ls);

    if(T[u<<1].ls==T[u<<1].r-T[u<<1].l+1)
        T[u].ls+=T[u<<1|1].ls;
    if(T[u<<1|1].rs==T[u<<1|1].r-T[u<<1|1].l+1)
        T[u].rs+=T[u<<1].rs;
}

int query(int u,int t)
{
    if(T[u].l==T[u].r||T[u].ms==0||T[u].ms==T[u].r-T[u].l+1)
    {
        return T[u].ms;
    }
    int m=(T[u].l+T[u].r)>>1;
    if(t<=m)
    {
        if(t>=T[u<<1].r-T[u<<1].rs+1)
            return query(u<<1,t)+query(u<<1|1,m+1);
        else
            return query(u<<1,t);
    }
    else
    {
        if(t<=T[u<<1|1].l+T[u<<1|1].ls-1)
            return query(u<<1|1,t)+query(u<<1,m);
        else
            return query(u<<1|1,t);
    }
}

int main()
{
    //freopen("C:\\Users\\Administrator\\Desktop\\kd.txt","r",stdin);
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        build(1,n,1);
        top=0;
        while(m--)
        {
            char c;
            int x;
            scanf(" %c",&c);
            if(c=='D')
            {
                scanf("%d",&x);
                st[top++]=x;
                update(1,x,0);
            }
            else if(c=='Q')
            {
                scanf("%d",&x);
                printf("%d\n",query(1,x));
            }
            else
            {
                if(x>0)
                {
                    x=st[--top];
                    update(1,x,1);
                }
            }
        }
    }
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值