HDU1754I Hate It(线段树维护区间最大值)

题目链接hdu1754

题目大意:给n个数以及q组操作,操作可能是查询或者更新。问区间最大值或更新。

解题思路:线段树裸题。看代码


AC代码(可能是写不好2800ms卡时限过得找个快点得板子)

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>

using namespace std;
const int maxn = (int)2e5+5;

struct Node {
	int l,r;
	int Max;
};

int val[maxn],n,q;
Node LTree[maxn << 2];

void Build (int l, int r, int idx) {
	LTree[idx].l = l;
	LTree[idx].r = r;
	if (l == r) {
		LTree[idx].Max = val[l];
		return ;
	}
	int mid = l + ((r - l) >> 1);
	Build(l, mid, idx << 1);
	Build(mid + 1, r, idx << 1 | 1);
	LTree[idx].Max = max(LTree[idx << 1].Max, LTree[idx << 1 | 1].Max); //PushUp
}

void Update (int k, int num, int idx) {
	if (LTree[idx].l == k && LTree[idx].r == k) {
		LTree[idx].Max = num;
		return ;
	}
	int mid = LTree[idx].l + ((LTree[idx].r - LTree[idx].l) >> 1); //注意不是二分要查询得区间QAQ
	if (k > mid) {
		Update(k, num, idx << 1 | 1);
	}else {
		Update(k, num, idx << 1);
	}
	LTree[idx].Max = max(LTree[idx << 1].Max, LTree[idx << 1 | 1].Max);
}

int Query (int l, int r, int idx) {
	if (l <= LTree[idx].l && r >= LTree[idx].r) {
		return LTree[idx].Max;
	}
	int mid = LTree[idx].l + ((LTree[idx].r - LTree[idx].l) >> 1);  //注意不是二分要查询得区间QAQ
	if (r <= mid) {
		return Query(l, r, idx << 1);
	}else if (l > mid){
		return Query(l, r, idx << 1 | 1);
	}else {
		return max(Query(l, mid, idx << 1), Query(mid + 1, r, idx << 1 | 1));
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	string cmd;int i,j;
	while (cin >> n >> q) {
		for (i = 1; i <= n; i++) {
			cin >> val[i];
		}
		Build(1, n, 1);
		while (q--) {
			cin >> cmd >> i >> j;
			if(cmd.at(0) == 'Q') {
				cout << Query(i, j, 1) << '\n';
			}else {
				Update(i, j, 1);
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胡同的诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值