pku 3264 Balanced Lineup线段树

第一次在pku做题,囧死了,这么一道题调了我N久

不过听说用RMQ-ST算法更高效,我用线段树做居然是4047ms

有点让我惊讶,居然可以慢成这样~~~~~~~~~

 

#include<stdio.h> #define N 50005 struct node{ int l; int r; int min; 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].min = 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].min = tree[L].min > tree[R].min? tree[R].min:tree[L].min; tree[k].max = tree[L].max > tree[R].max? tree[L].max:tree[R].max; return ; } int tree_search_min(int k,int left,int right) { int mid; int L,R; int lm = 1000005,rm = 1000005; if(left <= tree[k].l && right >= tree[k].r){ return tree[k].min; } L = 2*k; R = L+1; mid = (tree[k].l+tree[k].r)/2; if(left < mid) lm = tree_search_min(L,left,right); if(right > mid) rm = tree_search_min(R,left,right); return lm < rm? lm:rm; } int tree_search_max(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; } L = 2*k; R = L+1; mid = (tree[k].l+tree[k].r)/2; if(left < mid) lm = tree_search_max(L,left,right); if(right > mid) rm = tree_search_max(R,left,right); return lm > rm? lm:rm; } int main() { int n,q; int i; int a,b; while(scanf("%d %d",&n,&q) == 2){ for(i = 1;i <= n;i++) scanf("%d",arr+i); buid_tree(1,1,n+1); for(i = 0;i < q;i++){ scanf("%d %d",&a,&b); printf("%d/n",tree_search_max(1,a,b+1)-tree_search_min(1,a,b+1)); } } return 0; }

你可能感兴趣的:(算法,struct,tree,search)