RMQ区间最值问题--ST表,线段树,树状数组

ST表

附一个大佬的博文:  https://www.cnblogs.com/qq965921539/p/9608980.html

浅显易懂

void rmq(int n)
{
    for(int j = 1; (1<<j) <= n; j++)
        for(int i = 1; i+(1<<j)-1 <= n; i++)
            st[i][j] = min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
}

int ask(int l,int r)
{
    int k = log2(r-l+1);
    return min(st[l][k],st[r-(1<<k)+1][k]);
}

例题  hihoCoder 1068  https://hihocoder.com/problemset/problem/1068

参考代码

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 const int maxn = 1000010;
 6 int a[maxn];
 7 int st[maxn][20];
 8 
 9 void rmq(int n)
10 {
11     for(int j = 1; (1<<j) <= n; j++)
12         for(int i = 1; i+(1<<j)-1 <= n; i++)
13             st[i][j] = min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
14 }
15 
16 int ask(int l,int r)
17 {
18     int k = log2(r-l+1);
19     return min(st[l][k],st[r-(1<<k)+1][k]);
20 }
21 
22 int main()
23 {
24     ios::sync_with_stdio(false);
25     cin.tie(0);
26     cout.tie(0);
27     int n,m,l,r;
28     cin>>n;
29     for(int i = 1; i <= n; i++)
30     {
31         cin>>a[i];
32         st[i][0] = a[i];
33     }
34     rmq(n);
35     cin>>m;
36     for(int i = 1; i <= m; i++)
37     {
38         cin>>l>>r;
39         cout<<ask(l,r)<<endl;
40     }
41     return 0;
42 }
View Code

 

posted on 2019-08-08 10:19  By_布衣  阅读(136)  评论(0编辑  收藏  举报

导航