HDU1754 I Hate It

I Hate It

题目大意很明确,就是单点修改区间查询,用线段树即可。
代码如下:

#include
#include
#include
#define md mid = (tr[d].l + tr[d].r) / 2
#define lson ld = 2 * d
#define rson rd = 2 * d + 1
#define pushup tr[d].mx = max(tr[ld].mx, tr[rd].mx)
using namespace std;
const int maxn = 200005;
struct node
{
    int l, r, mx;
}tr[4 * maxn];
void build(int d, int l ,int r)
{
    tr[d].l = l, tr[d].r = r;
    if(l == r)
    {
        scanf("%d", &tr[d].mx);
        return;
    }
    int mid = (l + r) / 2;
    int lson, rson;
    build(ld, l, mid);
    build(rd, mid + 1, r);
   pushup;
}
void update(int d, int pos, int val)
{
    if(tr[d].l == tr[d].r && tr[d].l == pos)
    {
        tr[d].mx = val;
        return;
    }
    int md, lson, rson;
    if(pos <= mid)
    {
        update(ld, pos, val);
    }
    else update(rd, pos, val);
    pushup;
}
int query(int d, int l, int r)
{
    if(tr[d].l == l && tr[d].r == r)
    {
        return tr[d].mx;
    }
    int md, lson, rson;
    if(r <= mid) return query(ld, l, r);
    else if(l > mid)return query(rd, l, r);
    else return max(query(ld, l, mid), query(rd, mid + 1, r));
}
int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m))
    {
        build(1,1, n);
        char s[2];
        for(int i = 1; i <= m; i++)
        {
            scanf("%s", s);
            int x, y;
             scanf("%d%d", &x, &y);
            if(s[0] == 'Q')
            {
               printf("%d\n", query(1, x, y));
            }
            else update(1, x, y);
        }
    }
}

你可能感兴趣的:(线段树,数据结构)