题目来源:点击打开链接
这个博客里写的是线段树的知识点,解释的挺好的:点击打开链接
这是一题很基础的线段树,基本上套个模板就可以了
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 200005
int score[maxn];
struct
{
int l,r,max;
}node[4*maxn];
void buildtree(int left, int right, int u)
{
node[u].l = left;
node[u].r = right;
if(left == right)
{
node[u].max = score[left];//一开始max的最大值还不会处理
}
else
{
int mid = (left + right)/2;
buildtree(left, mid, 2*u);
buildtree(mid+1, right, 2*u+1);
node[u].max = max(node[2*u].max, node[2*u+1].max);
}
}
int query(int left, int right, int u)
{
if(node[u].l==left && node[u].r==right)
{
return node[u].max;
}
if(right<=node[2*u].r)
{
return query(left, right, 2*u);
}
if(left>=node[2*u+1].l)
{
return query(left, right, 2*u+1);
}
int mid = (node[u].l + node[u].r)/2;
return max(query(left, mid, 2*u), query(mid+1, right, 2*u+1));
}
void update(int stu, int sco, int u)
{
node[u].max = max(sco, node[u].max);
if(node[u].l == node[u].r) return;
if(stu<=node[2*u].r)
{
update(stu, sco, 2*u);
}
else
{
update(stu, sco, 2*u+1);
}
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&score[i]);
}
buildtree(1,n,1);
for(int i=1;i<=m;i++)
{
char c;
int b,e;
getchar();
scanf("%c%d%d",&c,&b,&e);
if(c=='Q')
{
printf("%d\n",query(b,e,1));
}
if(c=='U')
{
update(b,e,1);//更新数据
}
}
}
return 0;
}