刚学会了怎么建树、查询、更新后,就尝试着按照自己的思路解题,把语法错误改完后,然后就A了,经过几次修改,最后453MS,速度一般吧。
这题是基本的线段树的操作。对于线段树的入门知识,我看到有博客写的挺好的——【线段树】线段树入门之入门 ,我就不细说了。
参考代码:
#include<iostream> #include<stdio.h> using namespace std; int Max[524300],ql,qr,p,v; void build(int r,int L,int R) { int M; if (L==R) scanf("%d",&Max[r]); else { M=(L+R)>>1; build(r*2,L,M); build(r*2+1,M+1,R); Max[r]=max(Max[r*2],Max[r*2+1]); } } int query(int r,int L,int R) { int M; M=(L+R)>>1; if (ql<=L&&qr>=R) return Max[r]; else if (qr<=M) return query(r*2,L,M); else if (ql>=M+1) return query(r*2+1,M+1,R); else return max(query(r*2,L,M),query(r*2+1,M+1,R)); } void update(int r,int L,int R) { int M; M=(L+R)>>1; if (L==R) Max[r]=v; else { if (p<=M) update(r*2,L,M); else update(r*2+1,M+1,R); Max[r]=max(Max[r*2],Max[r*2+1]); } } int main() { int n,m,a,b; char ch; while (scanf("%d%d",&n,&m)!=EOF) { build(1,1,n); while (m--) { scanf("%s%d%d",&ch,&a,&b); if (ch=='Q') { ql=a;qr=b; printf("%d\n",query(1,1,n)); } else { p=a;v=b; update(1,1,n); } } } return 0; }