HDU 3308 - LCIS(线段树区间合并)

本文介绍了一种使用线段树数据结构解决最长连续上升子序列(LCIS)问题的方法,通过区间合并策略,有效地处理序列更新和查询操作,适用于大规模数据集。

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

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=3308

【题意】
给定长度为 n n n 的序列,有2种操作
U   A   B U \ A \ B U A B 将下标为 A A A 的元素修改为 B B B
Q   A   B Q \ A \ B Q A B 查询区间 [ A , B ] [A,B] [A,B] 的最长连续上升子序列长度(LCIS,不是LIS,必须连续)
下标从0开始 ( n , q &lt; = 1 0 5 , 元 素 值 &lt; = 1 0 5 ) (n,q&lt;=10^5,元素值&lt;=10^5) (n,q<=105<=105)

【思路】
线段树区间合并,区间维护5个属性, s u m sum sum 为最长连续上升子序列长度, s u m L sumL sumL 为以左端点为起点的最长连续上升子序列长度, s u m R sumR sumR 为以右端点为终点的最长连续上升子序列长度, L v Lv Lv 为左端点值, R v Rv Rv 为右端点值

#include<bits/stdc++.h>
#define node tree[id]
#define lson tree[id<<1]
#define rson tree[id<<1|1]
using namespace std;

const int maxn=100005;

struct Node{
	int sum,sumL,sumR;
	int Lv,Rv;
	Node(int s=0,int sL=0,int sR=0,int L=0,int R=0):sum(s),sumL(sL),sumR(sR),Lv(L),Rv(R){}
};

struct Tree{
	int left,right;
	int sum,sumL,sumR;
	int Lv,Rv;
}tree[maxn<<2];

int n,q;
int a[maxn];

void pushup(int id){
	node.Lv=lson.Lv;
	node.Rv=rson.Rv;
	node.sumL=lson.sumL;
	node.sumR=rson.sumR;
	node.sum=max(lson.sum,rson.sum);
	if(lson.Rv<rson.Lv){
		if(lson.sumL==lson.right-lson.left+1) node.sumL+=rson.sumL;
		if(rson.sumR==rson.right-rson.left+1) node.sumR+=lson.sumR;
		node.sum=max(node.sum,lson.sumR+rson.sumL);
	}
}

void build(int id,int le,int ri){
	node.left=le;
	node.right=ri;
	if(le==ri){
		node.sum=node.sumL=node.sumR=1;
		node.Lv=node.Rv=a[le];
		return;
	}
	int mid=(le+ri)>>1;
	build(id<<1,le,mid);
	build(id<<1|1,mid+1,ri);
	pushup(id);
}

Node query(int id,int le,int ri){
	if(node.left==le && node.right==ri){
		return Node(node.sum,node.sumL,node.sumR,node.Lv,node.Rv);
	}
	int mid=(node.left+node.right)>>1;
	if(ri<=mid) return query(id<<1,le,ri);
	else if(le>mid) return query(id<<1|1,le,ri);
	else{
		Node a=query(id<<1,le,mid);
		Node b=query(id<<1|1,mid+1,ri);
		Node ans;
		ans.Lv=a.Lv;
		ans.Rv=b.Rv;
		ans.sumL=a.sumL;
		ans.sumR=b.sumR;
		ans.sum=max(a.sum,b.sum);
		if(a.Rv<b.Lv){
			if(a.sumL==mid-le+1) ans.sumL+=b.sumL;
			if(b.sumR==ri-mid) ans.sumR+=a.sumR;
			ans.sum=max(ans.sum,a.sumR+b.sumL);
		}
		return ans;
	}
}

void update(int id,int pos,int val){
	if(node.left==node.right){
		node.sum=node.sumL=node.sumR=1;
		node.Lv=node.Rv=val;
		return;
	}
	int mid=(node.left+node.right)>>1;
	if(pos<=mid) update(id<<1,pos,val);
	else update(id<<1|1,pos,val);
	pushup(id);
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		scanf("%d%d",&n,&q);
		for(int i=1;i<=n;++i) scanf("%d",&a[i]);
		build(1,1,n);
		while(q--){
			char op[2];
			int x,y;
			scanf("%s%d%d",op,&x,&y);
			if(op[0]=='U'){
				update(1,x+1,y);
			}
			else{
				int ans=query(1,x+1,y+1).sum;
				printf("%d\n",ans);
			}
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值