上模板:
const int MAX = 999999;
struct treenode {
int val;//树节点值
int right, left;//左右区间
}tree[MAX];
int treeval[MAX];
int build(int root,int left,int right) {
tree[root].left = left;
tree[root].right = right;
if (left==right)
tree[root].val = treeval[left];
int mid = (left + right) / 2;
return tree[root].val =
max(build(root * 2, left, mid), build(root * 2 + 1, mid + 1, right));
}
int find(int root,int left,int right)
{
if (tree[root].left<left||tree[root].right>right)
return 0;
if (left <= tree[root].left && tree[root].right <= right)
return tree[root].val;
int a = find(2 * root, left, right);
int b = find(2 * root + 1, left, right);
return max(a, b);
}
int update(int root, int pos, int val)
{
if (pos < tree[root].left || tree[root].right < pos)
return tree[root].val;
if (tree[root].left == pos && tree[root].right == pos)
return tree[root].val = val;
int a = update(2 * root, pos, val);
int b = update(2 * root + 1, pos, val);
return tree[root].val = max(a, b);
}
最为简单的线段树模板,树节点需要维护的值只有节点值,节点左区间和节点右区间。