http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1174
第一次学线段树,感觉脑子里一片浆糊
#include<iostream> #include<algorithm> using namespace std; typedef long long ll; const int MAXN=1e4+5; struct node { ll l,r; ll val; }tree[4*MAXN]; int a[MAXN]; void build(int n,ll left,ll right) { tree[n].l=left; tree[n].r=right; if(left==right) tree[n].val=a[left]; else { ll mid=(left+right)/2; build(2*n,left,mid); build(2*n+1,mid+1,right); tree[n].val=max(tree[2*n].val,tree[2*n+1].val); } } ll ask(int n,ll left,ll right) { if(tree[n].l==tree[n].r) return tree[n].val; else { ll mid=(tree[n].r+tree[n].l)/2; if(right<=mid) return ask(n*2,left,right); else if(left>mid) return ask(n*2+1,left,right); else return max(ask(n*2,left,mid),ask(n*2+1,mid+1,right)); } } int main() { ll n,m,left,right; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; build(1,1,n); cin>>m; for(int i=1;i<=m;i++) { cin>>left>>right; ll ans=ask(1,left+1,right+1); cout<<ans<<endl; } return 0; }