HDU 1754
这同样是一道线段树的入门题,与HDU 1166非常类似,都是了解其基本的操作。不同是这一道是求最大值,所以query的操作略有不同。值得注意的是,节点数应该为题目所给的MAXN*4(HDU 1166也是)。这一点我还没明白是为什么。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX_STUDENTS 200002 #define INF 1000000 struct node { int left; int right; int max; }studnt[MAX_STUDENTS*4]; int query(int,int,int); void update(int,int,int,int),build(int,int,int); int get_max(int,int); int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { memset(studnt,0,sizeof(studnt)); build(1,1,n); int i; for(i=1;i<=n;i++) { int tem; scanf("%d",&tem); update(1,i,i,tem); } char ope[3]; for(i=0;i<m;i++) { scanf("%s",ope); int a,b,ans; scanf("%d%d",&a,&b); if(ope[0]=='Q') { ans=query(1,a,b); printf("%d\n",ans); } else { update(1,a,a,b); } } } return 0; } void build(int root,int le,int ri) { studnt[root].left=le; studnt[root].right=ri; if(le==ri) return ; int mid=(le+ri)/2; build(2*root,le,mid); build(2*root+1,mid+1,ri); } void update(int root,int le,int ri,int val) { if(le==studnt[root].left&&ri==studnt[root].right) { studnt[root].max=val; return ; } if(le>studnt[root].right||ri<studnt[root].left) { return ; } update(root*2,le,ri,val); update(root*2+1,le,ri,val); studnt[root].max=get_max(studnt[root*2].max,studnt[root*2+1].max); } int query(int root,int le,int ri) { if(le<=studnt[root].left&&ri>=studnt[root].right) { return studnt[root].max; } if(le>studnt[root].right||ri<studnt[root].left) { return -INF; } return get_max(query(2*root,le,ri),query(2*root+1,le,ri)); } int get_max(int a,int b) { return a>b?a:b; }