【维护区间最长连续子序列 && 线段树 && 区间归并】HDU - 1540 Tunnel Warfare

本文介绍了一种使用段式树解决包含破坏点、恢复点及查询最长连续子序列问题的方法。通过维护左右最长连续子序列及连续状态,利用栈记录破坏点,实现了高效的更新与查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

输入n,m。分别代表有一个1-n的序列,接下来m行,分别有三种操作。
D x: 将x这个点破坏掉,x这个点就会破坏连续子序列。Q x: 询问包括点x在内的最长连续子序列长度(一开始的时候是n)。R: 恢复最近一个被破坏的点。

思路:

我们需要维护一个区间里面,从左向右最长的连续子序列lmax, 从右向左最长的连续子序列rmax, 同时用一个变量ok标记该区间是否连续。因为有恢复最近一个被破坏的点,所以我们可以使用栈存破坏掉的点。具体的实现看代码。

#include<bits/stdc++.h>
using namespace std;
#define lson root<<1
#define rson root<<1|1
#define MID int mid = (l + r) / 2
#define N 50000
struct node
{
    int lmax, rmax, ok;
    node operator + (const node &b) const{//区间归并
        node res;
        res.lmax = lmax;
        if(ok) res.lmax += b.lmax;//左区间连续,所以加上右区间,左向右最长的连续子序列lmax
        res.rmax = b.rmax;
        if(b.ok) res.rmax += rmax;//右区间连续,同理。
        res.ok = ok && b.ok;//当前区间连续不连续
        return res;
    }
};
node a[4 * N];
int lok, rok;//判断当前询问的num点,左边连续不连续,右边连续不连续。连续为1,不连续为0
void build(int root, int l, int r)
{
    if(l == r)//一开始肯定是连续的,所以全为1
    {
        a[root].lmax = a[root].rmax = a[root].ok = 1;
        return;
    }
    MID;
    build(lson, l, mid);
    build(rson, mid + 1, r);
    a[root] = a[lson] + a[rson];//区间归并
}
void updata(int root, int l, int r, int pos, int v)//更新
{
    if(l == r)
    {
        a[root].lmax = a[root].rmax = a[root].ok = v;
        return;
    }
    MID;
    if(pos <= mid) updata(lson, l, mid, pos, v);
    else updata(rson, mid + 1, r, pos, v);
    a[root] = a[lson] + a[rson];
}
int query(int root, int l, int r, int pos)
{
    if(l == r)
    {
        lok = rok = a[root].ok;//初始化为ok
        return a[root].lmax;
    }
    int ans;
    MID;
    if(pos <= mid)//左区间
    {
        ans = query(lson, l, mid, pos);
        if(rok) ans += a[rson].lmax;//如果num右边连续,更新ans
        rok = rok && a[rson].ok;//更新rok
    }
    else//右区间
    {
        ans = query(rson, mid + 1, r, pos);
        if(lok) ans += a[lson].rmax;//如果num左边连续,更新ans
        lok = lok && a[lson].ok;//更新lok
    }
    return ans;
}
int main()
{
    int n, m, num;
    char s[2];
    while(~scanf("%d %d", &n, &m))
    {
        stack<int> q;
        build(1, 1, n);//初始化
        while(m--)
        {
            scanf("%s", s);
            if(s[0] == 'D')
            {
                scanf("%d", &num);
                updata(1, 1, n, num, 0);//将num点全为0
                q.push(num);//栈存起来
            }
            else if(s[0] == 'Q')
            {
                scanf("%d", &num);//求包括num点的最长连续子序列
                printf("%d\n", query(1, 1, n, num));
            }
            else
            {
                updata(1, 1, n, q.top(), 1);//恢复
                q.pop();//恢复后弹出
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值