HDU 1754 I Hate It

本文介绍了段树的构建、更新和查询操作,通过实例详细解释了如何使用段树进行高效的区间最大值查找和更新。

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

Simple segment tree;

The portal:http://acm.hdu.edu.cn/showproblem.php?pid=1754


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 200005;

struct Node {
	int value;
	int Left;
	int Right;
}Segment_Tree[MAXN<<2];

int a[MAXN];
int cnt ;

void Build_Tree(int Left,int Right,int Now) {
	Segment_Tree[Now].Left = Left;
	Segment_Tree[Now].Right = Right;
	if(Left == Right) {
		Segment_Tree[Now].value = a[cnt++];
		return ;
	}
	int Mid = (Left + Right) >> 1;
	Build_Tree(Left,Mid,Now<<1);
	Build_Tree(Mid+1,Right,Now<<1|1);
	Segment_Tree[Now].value = max(Segment_Tree[Now<<1].value,Segment_Tree[Now<<1|1].value);
}

void Update_Tree(int Left,int Right,int Now,int position,int change_value) {
	if(Left == Right) {
		Segment_Tree[Now].value = change_value;
		return;
	}
	int Mid = (Left + Right) >> 1;
	if(position > Mid) {
		Update_Tree(Mid+1,Right,Now<<1|1,position,change_value);
	}
	else {
		Update_Tree(Left,Mid,Now<<1,position,change_value);
	}
	Segment_Tree[Now].value = max(Segment_Tree[Now<<1].value,Segment_Tree[Now<<1|1].value);
}

int Query_Tree(int Left,int Right,int Now,int Left_Edge,int Right_Edge) {
	int Query_Ans = 0;
	if(Left >= Left_Edge && Right <= Right_Edge) {
		return Segment_Tree[Now].value;
	}
	int Mid = (Left + Right) >> 1;
	if(Mid >= Left_Edge) {
		Query_Ans = max(Query_Ans,Query_Tree(Left,Mid,Now<<1,Left_Edge,Right_Edge));
	}
	if(Mid < Right_Edge) {
		Query_Ans = max(Query_Ans,Query_Tree(Mid+1,Right,Now<<1|1,Left_Edge,Right_Edge));
	}
	return Query_Ans;
}

void Deal_with() {
	int n,m;
	while(~scanf("%d %d",&n,&m)) {
		for(int i = 1 ; i <= n ; i++) {
			scanf("%d",a+i);
		}
		cnt = 1;
		Build_Tree(1,n,1);
		char tempc;
		int position,value;
		for(int i = 1 ; i <= m ; i++) {
			getchar();
			scanf("%c %d %d",&tempc,&position,&value);
			if(tempc == 'U') {
				Update_Tree(1,n,1,position,value);
			}
			else {
				printf("%d\n",Query_Tree(1,n,1,position,value));
			}
		}
	}
}

int main(void) {
	//freopen("a.in","r",stdin);
	Deal_with();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值