hdu-1754 I Hate It---线段树模板题

题目链接:

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

题目大意:

求区间最大值+单点修改

解题思路:

直接套用模板即可

 1 #include<bits/stdc++.h>
 2 #define MID(l, r) (l + (r - l) / 2)
 3 #define lson(o) (o * 2)
 4 #define rson(o) (o * 2 + 1)
 5 using namespace std;
 6 typedef long long ll;
 7 const int INF = 1e9 +7;
 8 const int maxn = 1e6 + 10;
 9 int a[maxn];
10 struct node
11 {
12     int l, r, mmax, mmin, sum;
13 }tree[maxn];
14 void build(int o, int l, int r)
15 {
16     tree[o].l = l, tree[o].r = r;
17     if(l == r)
18     {
19         tree[o].mmax = tree[o].mmin = tree[o].sum = a[l];
20         return;
21     }
22     int m = MID(l, r);
23     int lc = lson(o), rc = rson(o);
24     build(lc, l, m);
25     build(rc, m + 1, r);
26     tree[o].mmax = max(tree[lc].mmax, tree[rc].mmax);
27     tree[o].mmin = min(tree[lc].mmin, tree[rc].mmin);
28     tree[o].sum = tree[lc].sum + tree[rc].sum;
29 }
30 int ql, qr;//查询区间[ql, qr]中的max,min,sum
31 int ans_max, ans_min, ans_sum;
32 void query_init()//查询前,将全局变量初始化
33 {
34     ans_max = -INF;
35     ans_min = INF;
36     ans_sum = 0;
37 }
38 void query(int o)
39 {
40     if(ql <= tree[o].l && qr >= tree[o].r)//[L, R]包含在[ql, qr]区间内,直接用该节点的信息,达到线段树查询快的操作
41     {
42         ans_max = max(ans_max, tree[o].mmax);
43         ans_min = min(ans_min, tree[o].mmin);
44         ans_sum += tree[o].sum;
45         return;
46     }
47     int m = MID(tree[o].l, tree[o].r);
48     if(ql <= m)query(lson(o));
49     if(qr > m)query(rson(o));
50 }
51 //单点更新,a[p] = v;
52 int p, v;
53 void update(int o)
54 {
55     if(tree[o].l == tree[o].r)
56     {
57         tree[o].mmax = v;
58         tree[o].mmin = v;
59         tree[o].sum = v;
60         return;
61     }
62     int m = MID(tree[o].l, tree[o].r);
63     int lc = lson(o), rc = rson(o);
64     if(p <= m)update(lc);
65     else update(rc);
66     tree[o].mmax = max(tree[lc].mmax, tree[rc].mmax);
67     tree[o].mmin = min(tree[lc].mmin, tree[rc].mmin);
68     tree[o].sum = tree[lc].sum + tree[rc].sum;
69 }
70 int main()
71 {
72     int n, m;
73     while(scanf("%d%d", &n, &m) != EOF)
74     {
75         for(int i = 1; i <= n; i++)scanf("%d", &a[i]);
76         build(1, 1, n);
77         char s[5];
78         int x, y;
79         while(m--)
80         {
81             scanf("%s%d%d", s, &x, &y);
82             if(s[0] == 'Q')
83             {
84                 ql = x, qr = y;
85                 query_init();
86                 query(1);
87                 printf("%d\n", ans_max);
88             }
89             else if(s[0] == 'U')
90             {
91                 p = x, v = y;
92                 update(1);
93             }
94         }
95     }
96     return 0;
97 }

 

posted @ 2018-05-11 15:39  _努力努力再努力x  阅读(124)  评论(0编辑  收藏  举报