标签:nyoj1185 nyoj 1185 线段树求区间最值
对于不懂线段树的,先看为这篇文章理解下。点击打开链接
这道题普通方法 ,TLE。
如果C等于1,输出第L个数到第R个数之间的最小值;
如果C等于2,输出第L个数到第R个数之间的最大值;
如果C等于3,输出第L个数到第R个数之间的最小值与最大值的和。
2 4 1 3 2 4 2 1 1 4 2 2 3 5 1 2 3 4 5 1 3 1 5
1 3 6
#include <stdio.h> #include <algorithm> #define N 10005 using namespace std; struct node { int left,right,min,max; }c[N*4]; int a[N]; void buildtree(int l,int r,int root) { c[root].left=l; c[root].right=r; if(l==r) { c[root].min=c[root].max=a[l]; return ; } int mid=(l+r)/2; buildtree(l,mid,root*2); buildtree(mid+1,r,root*2+1); c[root].min=min(c[root*2].min,c[root*2+1].min); c[root].max=max(c[root*2].max,c[root*2+1].max); } void findtree(int l,int r,int root,int &min1,int &max1) { if(c[root].left==l&&c[root].right==r) { min1=c[root].min; max1=c[root].max; return ; } int mid=(c[root].left+c[root].right)/2; if(mid<l) findtree(l,r,root*2+1,min1,max1); else if(mid>=r) findtree(l,r,root*2,min1,max1); else { int min2,max2; findtree(l,mid,root*2,min1,max1); findtree(mid+1,r,root*2+1,min2,max2); min1=min(min1,min2); max1=max(max1,max2); } } int main() { int t,n,x,l,r,sum,m,min1,max1; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); buildtree(1,n,1); scanf("%d",&m); while(m--) { scanf("%d %d %d",&x,&l,&r); findtree(l,r,1,min1,max1); if(x==1) printf("%d\n",min1); if(x==2) printf("%d\n",max1); if(x==3) printf("%d\n",min1+max1); } } return 0; }
nyoj1185 最大最小值 (线段树求区间最大值和最小值)
标签:nyoj1185 nyoj 1185 线段树求区间最值
原文地址:http://blog.csdn.net/su20145104009/article/details/45562121