模板
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <iostream> 5 using namespace std; 6 const int MAXN = 100117; 7 int n,query; 8 int num[MAXN]; 9 10 int F_Min[MAXN][20],F_Max[MAXN][20]; 11 12 void Init() 13 { 14 for(int i = 1; i <= n; i++) 15 { 16 F_Min[i][0] = F_Max[i][0] = num[i]; 17 } 18 19 for(int i = 1; (1<<i) <= n; i++) //按区间长度递增顺序递推 20 { 21 for(int j = 1; j+(1<<i)-1 <= n; j++) //区间起点 22 { 23 F_Max[j][i] = max(F_Max[j][i-1],F_Max[j+(1<<(i-1))][i-1]); 24 F_Min[j][i] = min(F_Min[j][i-1],F_Min[j+(1<<(i-1))][i-1]); 25 } 26 } 27 } 28 29 int Query_max(int l,int r) 30 { 31 int k = (int)(log(double(r-l+1))/log((double)2)); 32 return max(F_Max[l][k], F_Max[r-(1<<k)+1][k]); 33 } 34 35 int Query_min(int l,int r) 36 { 37 int k = (int)(log(double(r-l+1))/log((double)2)); 38 return min(F_Min[l][k], F_Min[r-(1<<k)+1][k]); 39 } 40 41 int main() 42 { 43 int a,b; 44 scanf("%d %d",&n,&query); 45 for(int i = 1; i <= n; i++) 46 scanf("%d",&num[i]); 47 Init(); 48 while(query--) 49 { 50 scanf("%d %d",&a,&b); 51 printf("区间%d到%d的最大值为:%d ",a,b,Query_max(a,b)); 52 printf("区间%d到%d的最小值为:%d ",a,b,Query_min(a,b)); 53 printf("区间%d到%d的最大值和最小值只差为:%d ",a,b,Query_max(a,b)-Query_min(a,b)); 54 } 55 return 0; 56 }
http://blog.csdn.net/u012860063/article/details/40752197