树状数组最值

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

const int MAXN = 4e3;
int num[MAXN], tree[MAXN];
int n, m;
int lowbit(int x)
{
        return x & (-x);
}
void updata(int x)
{
        int lx, i;
        while (x <= n)
        {
                tree[x] = num[x];
                lx = lowbit(x);
                for (i = 1; i < lx; i <<= 1)
                {
                        tree[x] = max(tree[x], tree[x - i]);
                }
                x += lowbit(x);
        }
}
int query(int x, int y)
{
        int ans = 0;
        while (y >= x)
        {
                ans = max(num[y], ans);
                y --;
                for (; y - lowbit(y) >= x; y -= lowbit(y))
                {
                        ans = max(tree[y], ans);
                }
        }
        return ans;
}
int main()
{
        int i, j, x, y, ans;
        while (cin >> n && n)
        {
                int ans = 0;
                int cur;
                mem(tree, 0);
                for (i = 1; i <= n; i++)
                {
                        scanf("%d", &num[i]);
                        updata(i);
                }
        }
        for (i = 1; i <= m; i++)
        {
                if (c == 'Q')  //查询
                {
                        scanf("%d%d", &x, &y);
                        ans = query(x, y);
                        printf("%d\n", ans);
                }
                else if (c == 'U')  //修改
                {
                        scanf("%d%d", &x, &y);
                        num[x] = y;
                        updata(x);
                }
        }

        return 0;
}

 

posted @ 2017-10-03 19:01  Aragaki  阅读(149)  评论(0编辑  收藏  举报