节点保存区间的最大值,父结点保存左右结点中大的那个,建树时比较下就是了
#include<stdio.h> #define N 200005 struct node { int l; int r; int max; }; node tree[3*N]; int arr[N]; void buid_tree(int k,int left,int right) { int mid; int L,R; tree[k].l = left; tree[k].r = right; if(right - left == 1){ tree[k].max = arr[left]; return ; } L = 2*k; R = L+1; mid = (tree[k].l+tree[k].r)/2; buid_tree(L,left,mid); buid_tree(R,mid,right); tree[k].max = tree[L].max > tree[R].max? tree[L].max:tree[R].max; return ; } int tree_search(int k,int left,int right) { int mid; int L,R; int lm = 0,rm = 0; if(left <= tree[k].l && right >= tree[k].r){ return tree[k].max; } mid = (tree[k].l+tree[k].r)/2; L = 2*k; R = L+1; if(left < mid) lm = tree_search(L,left,right); if(right > mid) rm = tree_search(R,left,right); return lm > rm? lm:rm; } void tree_insert(int k,int left,int right,int data) { int mid; int L,R; if(left <= tree[k].l && right >= tree[k].r){ tree[k].max = data; return ; } mid = (tree[k].r+tree[k].l)/2; L = 2*k; R = L+1; if(left < mid) tree_insert(L,left,right,data); if(right > mid) tree_insert(R,left,right,data); tree[k].max = tree[L].max > tree[R].max? tree[L].max:tree[R].max; return ; } int main() { int n,m; int i; char ch; int a,b; while(scanf("%d %d",&n,&m) == 2){ for(i = 1;i <= n;i++) scanf("%d",&arr[i]); buid_tree(1,1,n+1); for(i = 0;i < m;i++){ getchar(); ch = getchar(); if(ch == 'Q'){ scanf("%d %d",&a,&b); printf("%d/n",tree_search(1,a,b+1)); } if(ch == 'U'){ scanf("%d %d",&a,&b); tree_insert(1,a,a+1,b); } } } return 0; }