HDU 1754(线段树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754

区间求和问题~~~

代码:

#include <stdio.h>
#define N 200002
#define M 5002
#define L(x) ((x)<<1)
#define R(x) ((x)<<1|1)

typedef struct
{
    int lson, rson;
    int val;
}   seg_tree;
seg_tree s[N<<2];
int num[N];

int build(int left, int right, int idx)
{
    s[idx].lson = left;
    s[idx].rson = right;
    if(left == right)
    {
        return s[idx].val = num[left];
    }
    int mid = (s[idx].lson + s[idx].rson) / 2;
    int a, b;
    return s[idx].val = ((a = build(left, mid, L(idx))) > (b = build(mid + 1, right, R(idx))) ? a : b);
}

void update(int id, int val, int idx)
{
    if(s[idx].lson == s[idx].rson)
    {
        s[idx].val = val;
        return;
    }
    int mid = (s[idx].lson + s[idx].rson) / 2;
    if(id <= mid)
    {
        update(id, val, L(idx));
    }
    else
    {
        update(id, val, R(idx));
    }
    s[idx].val =  s[L(idx)].val > s[R(idx)].val ? s[L(idx)].val : s[R(idx)].val;
}

int query(int left, int right, int idx)
{
    if(left == s[idx].lson && s[idx].rson == right)
    {
        return s[idx].val;
    }
    int mid = (s[idx].lson + s[idx].rson) / 2;
    if(right <= mid)
    {
        return query(left, right, L(idx));
    }
    else if(left > mid)
    {
        return query(left, right, R(idx));
    }
    else
    {
        int a, b;
        return  (a = query(left, mid, L(idx))) > (b = query(mid + 1, right, R(idx))) ? a : b;
    }
}

int main()
{
    int n, m;
    int i, j;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        for(i = 1; i <= n; i++)
        {
            scanf("%d", &num[i]);
        }
        build(1, n, 1);
        for(j = 0; j < m; j++)
        {
            char c;
            int a, b;
            scanf("%s %d %d", &c, &a, &b);
            switch(c)
            {
                case 'U':
                    update(a, b, 1);
                    break;
                case 'Q':
                    printf("%d\n", query(a, b, 1));
                    break;
            }
        }
    }
}
posted @ 2012-09-03 19:16  山路水桥  阅读(159)  评论(0编辑  收藏  举报