http://hihocoder.com/problemset/problem/1067
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cmath> 6 #include <algorithm> 7 #include <string> 8 #include <queue> 9 #include <stack> 10 #include <vector> 11 #include <map> 12 #include <set> 13 #include <functional> 14 #include <cctype> 15 #include <time.h> 16 17 using namespace std; 18 19 struct Sparse_Table { 20 static const int MAXN = (int)1e6+55; 21 static const int MAXM = 21; 22 23 int ST[MAXM][MAXN]; 24 int bit[MAXN]; 25 int n; 26 27 void init() { //初始化bit数组,放在程序开始的时候,只需做一次 28 bit[0] = bit[1] = bit[1] = 0; 29 for (int i = 1; (i<<1)<MAXN; i++) 30 bit[i<<1] = bit[i<<1|1] = bit[i]+1; 31 } 32 33 void initTable(int a[], int n) { 34 this->n = n; 35 for (int i = 0; i < n; i++) 36 ST[0][i] = a[i]; 37 int hight = bit[n]; 38 for (int i = 0; i < hight; i++) 39 for (int j = 0; j+(1<<i) < n; j++) 40 ST[i+1][j] = min(ST[i][j], ST[i][j+(1<<i)]); 41 } 42 43 inline int Query(int l, int r) { 44 if (l==r) return ST[0][l]; 45 int h = bit[r-l+1]; 46 return min(ST[h][l], ST[h][r-(1<<h)+1]); 47 } 48 49 void output() { 50 int h = bit[n]; 51 for (int i = 0; i <= h; i++) { 52 for (int j = 0; j < n; j++) 53 printf("%d ", ST[i][j]); 54 puts(""); 55 } 56 } 57 }; 58 59 const int INF = 1<<30; 60 const int MAXN = 1e6+55; 61 62 Sparse_Table solver; 63 int a[MAXN]; 64 int n, Q; 65 66 int main() { 67 #ifdef Phantom01 68 freopen("1068.txt", "r", stdin); 69 #endif //Phantom01 70 71 solver.init(); 72 73 while (scanf("%d", &n)!=EOF) { 74 for (int i = 0; i < n; i++) scanf("%d", &a[i]); 75 76 solver.initTable(a, n); 77 scanf("%d", &Q); 78 for (int i = 0; i < Q; i++) { 79 int l, r; 80 scanf("%d%d", &l, &r); 81 printf("%d\n", solver.Query(l-1, r-1)); 82 } 83 } 84 85 return 0; 86 }