1. 程式人生 > >樹狀數組最值

樹狀數組最值

tdi iostream max div stream sca pri 修改 log

#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; }

樹狀數組最值