【HDU1754】I Hate It(线段树)

本文详细介绍了一种高效的数据结构实现方法,用于处理单点更新和区间最大值查询的问题。通过使用递归构建和更新线段树,可以快速地完成对特定范围内的数值更新和查询操作,适用于解决大规模数据集上的动态规划问题。

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

update:单点替换 query:区间最值

 

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cstdio>
 5 #include <numeric>
 6 #include <cctype>
 7 #include <algorithm>
 8 #include <cmath>
 9 #include <vector>
10 #include <climits>
11 using namespace std;
12 
13 const int maxn = 2e5 + 10;
14 int maxv[maxn * 3];
15 
16 void update (int p, int v, int o, int L, int R) {
17     int M = L + ((R - L) >> 1);
18     if (L == R) {
19         maxv[o] = v;
20     } else {
21         if (p <= M) {
22             update (p, v, o << 1, L, M);
23         } else {
24             update (p, v, (o << 1) | 1, M + 1, R);
25         }
26         maxv[o] = max (maxv[o * 2], maxv[o << 1 | 1]);
27     }
28 }
29 
30 int query (int ql, int qr, int o, int L, int R) {
31     int M = L + (R - L) / 2, ans = INT_MIN;
32     if (ql <= L && R <= qr) {
33         return maxv[o];
34     }
35     if (ql <= M) {
36         ans = max (ans, query (ql, qr, o << 1, L, M));
37     }
38     if (M < qr) {
39         ans = max (ans, query (ql, qr, o << 1 | 1, M + 1, R));
40     }
41     return ans;
42 }
43 
44 int main () {
45     int n, ask_n, x, a, b;
46     char op[5];
47     while (~scanf ("%d%d", &n, &ask_n)) {
48         memset (maxv, 0, sizeof(maxv));
49         for (int i = 1; i <= n; ++ i)  {
50             scanf ("%d", &x);
51             update (i, x, 1, 1, n);
52         }
53 
54         while (ask_n --) {
55             scanf ("%s %d %d", op, &a, &b);
56 
57             if (op[0] == 'Q') {
58                 printf ("%d\n", query (a, b, 1, 1, n));
59             } else if (op[0] == 'U') {
60                 update (a, b, 1, 1, n);
61             }
62         }
63     }
64     return 0;
65 }

 

转载于:https://www.cnblogs.com/Destiny-Gem/p/3875629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值