题意如下:
给你从1到N 每个学生的成绩。 有M个操作,操作分为两种,一种是查询Q X Y(查询从X学生到Y学生的最高分数) 另一种就是U X Y(将学生X的成绩改为Y);
一道明显的线段树题目 ,过程也是比较明确,建树、查询最大值、更新树.
附上代码:
#include <stdio.h>
#include <iostream>
#include <cstring>
#define max(x,y) (x>y?x:y)
//定义节点结构体
typedef struct
{
int Max;
int left,right;
}Node;
int sc[200010];
Node tree[4000200];
int build(int root,int left,int right)
{ int mid;
tree[root].left=left;
tree[root].right=right;
if(left==right)//如果该节点的左右端点相等 则代表已经到了底端 所以该节点的最大值为已经输入的值
{
return tree[root].Max=sc[left];
}
mid=(left+right)/2;
int a,b;
a=build(2*root,left,mid);
b=build(2*root+1,mid+1,right);
return tree[root].Max=max(a,b);
}
//更新树的pos节点 将其的分数改为score 并且更新所有的Max
int update(int root,int pos,int score)
{
if(tree[root].left>pos || tree[root].right<pos ) return tree[root].Max;
if(tree[root].left==pos && tree[root].right==pos ) return tree[root].Max=score;
int a,b;
a=update(2*root,pos,score);
b=update(2*root+1,pos,score);
tree[root].Max=max(a,b);
return tree[root].Max;
}
int findmax(int root,int left,int right)
{
if(right<tree[root].left || left>tree[root].right) return 0;
if(left<=tree[root].left&&right>=tree[root].right) return tree[root].Max;
int a=findmax(2*root,left,right);
int b=findmax(2*root+1,left,right);
return max(a,b);
}
int main()
{
//freopen("in.in","r",stdin);
int N,M;
while(scanf("%d %d",&N,&M)!=EOF)
{
for(int i=1;i<=N;i++)
scanf("%d",&sc[i]);
build(1,1,N);
for(int i=1;i<=M;i++){getchar () ;
char ch;
int a,b;
scanf("%c %d %d",&ch,&a,&b);
if(ch=='U')
{ sc[a]=b;
update(1,a,b);
}
if(ch=='Q')
{
printf("%d\n",findmax(1,a,b));
}
}
}
return 0;
}