题目描述:
裸的选段树
包括 单点更新 区间查询 建树
code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
const int MAXNODE = 1 << 19;
const int MAXN = 2e6 + 10;
struct NODE {
int left, right;
int value;
}node[MAXNODE];
int father[MAXN];//表示每个节点的序号
void Buildtree(int i,int left,int right)
{
node[i].left = left;
node[i].right = right;
node[i].value = 0;
if (left == right)
{
father[left] = i;
return;
}
Buildtree(i<<1,left,(int)(floor(right+left)/2.0));
Buildtree((i << 1) + 1, (int)(floor(right + left) / 2.0)+1, right);
}
void UpdateTree(int ri)//从底部开始更新 单点更新
{
if (ri == 1)return;//如果已经更新到第一个节点就返回
int fi = ri / 2;
int a = node[fi<<1].value;
int b = node[(fi<<1)+1].value;
node[fi].value = max(a, b);
UpdateTree(ri / 2);
}
int MAX;
void Querry(int i,int left,int right)//查找区间最大值
{
if (node[i].left ==left&& node[i].right==right)//i号分支点的区间包含等于所查找的区间
{
MAX = max(node[i].value, MAX);
return;
}
i = i << 1;
if(left<= node[i].right)
if (right <= node[i].right)//所查找区间包含在左子树里面
{
Querry(i, left, right);
}
else//一半包含在左子树里面
{
Querry(i, left, node[i].right);
}
i++;
if(right>=node[i].left)
if (left >= node[i].left)//所查找的区间包含在右子树里面
{
Querry(i, left, right);
}
else //另一半包含在右子树里
{
Querry(i, node[i].left, right);
}
}
int main()
{
ios::sync_with_stdio(false);//关闭缓冲区
int n, m, k;
while (cin >> n >> m)
{
Buildtree(1,1,n);
for (int i = 1; i <= n; i++)
{
cin>>k;
node[father[i]].value = k;
UpdateTree(father[i]);
}
string op;
int a, b;
while (m--)
{
cin >> op >> a >> b;
if (op[0] == 'Q')
{
MAX = 0;
Querry(1, a, b);//从第一个节点开始查找
cout << MAX << endl;
}
if (op[0] == 'U')
{
node[father[a]].value = b;
UpdateTree(father[a]);
}
}
}
}