http://blog.csdn.net/cnyali/article/details/52228846
- #include <iostream>
- #include <cmath>
- #define maxn 10005
- using namespace std;
- int maxsum[maxn][20], minsum[maxn][20];
- void RMQ(int num) //预处理->O(nlogn)
- {
- int i, j;
- for(j = 1; j < 20; ++j)
- for(i = 1; i <= num; ++i)
- if(i + (1 << j) -1 <= num)
- {
- maxsum[i][j] = max(maxsum[i][j-1], maxsum[i+(1 << j)][j-1]);
- minsum[i][j] = min(minsum[i][j-1], minsum[i+(1 << j)][j-1]);
- }
- }
- int main()
- {
- int i, j, num, t, query;
- cin >> t;
- while(t--)
- {
- cin >> num >> query;
- for(i = 0; i < num; i++)
- {
- cin >> maxsum[i][0];
- minsum[i][0] = maxsum[i][0];
- }
- RMQ(num);
- int start, end, maxl, minl;
- while(query--) //o(1) 查询
- {
- cin >> start >> end;
- int k = (int)((log(end-start+1))/log(2.0));
- maxl = max(maxsum[start][k], maxsum[end-(1 << k)+1][k]);
- minl = min(minsum[start][k], minsum[end-(1 << k)+1][k]);
- cout << maxl << minl << endl;
- }
- }
- return 0;
- }