poj 3264 Balanced Lineup RMQ

emmm,第一遍的时候用的是C++的cin ,cout 果不其然,超时。

然后全部改为scanf和printf,卡过

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cmath>
 5 using namespace std;
 6 
 7 const  int maxn = 50005;
 8 int a[maxn];
 9 int n, m;
10 int minsum[maxn][50];
11 int maxsum[maxn][50];
12 
13 void RMQ(int num) //预处理->O(nlogn)  
14 {
15     //初始化
16     for (int i = 1; i <= num; i++){
17         minsum[i][0] = a[i];
18         maxsum[i][0] = a[i];
19     }
20 
21     for (int j = 1; j < 25; j++)
22     for (int i = 1; i <= num; i++)
23     if (i + (1 << j) - 1 <= num)
24     {
25         maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);
26         minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
27     }
28 }
29 
30 //查询
31 int getmin(int x, int y){
32     int k = (int)(log((double)(y - x + 1)) / log(2.0));
33     return min(minsum[x][k], minsum[y - (1 << k) + 1][k]);
34 }
35 
36 int getmax(int x, int y){
37     int k = (int)(log((double)(y - x + 1)) / log(2.0));
38     return max(maxsum[x][k], maxsum[y - (1 << k) + 1][k]);
39 }
40 
41 int main(){
42     scanf("%d%d", &n, &m);
43     for (int i = 1; i <= n; i++){
44         scanf("%d", &a[i]);
45     }
46     //预处理O(nlogn)
47     RMQ(n);
48 
49     while (m--){
50         int x, y;
51         scanf("%d%d", &x, &y);
52         int Min = getmin(x, y);
53         int Max = getmax(x, y);
54         int ans = Max - Min;
55 //        cout << "*" << Min << " " << Max << endl;
56         printf("%d\n", ans);
57     }
58     //system("pause");
59     return 0;
60 }

 

posted @ 2017-11-09 19:56  ouyang_wsgwz  阅读(109)  评论(0编辑  收藏  举报