倍增 1270. 數列區間最大值

輸入一串數字,給你 M 個詢問,每次詢問就給你兩個數字 X,Y,要求你說出 X 到 Y 這段區間內的最大數。

輸入格式
第一行兩個整數 N,M 表示數字的個數和要詢問的次數;

接下來一行爲 N 個數;

接下來 M 行,每行都有兩個整數 X,Y。

#include <bits/stdc++.h>

using namespace std;
const int N=1e5+5;
int n,m,a[N],st[N][20],l,r;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for(int i=1;i<=n;i++)
        cin >> a[i];
    for(int i=1;i<=n;i++)
        st[i][0]=a[i];
    for(int j=1;(1<<j)<=n;j++)//n爲個數
    {
       	for(int i=1;(1<<j)<=n-i+1;i++)//n爲下標
        {
            //(1<<j)都是總個數
            st[i][j]=max(st[i][j-1],st[i+(1<<(j-1))][j-1]);
        }
    }
    while(m--)
    {
        cin >> l >> r;
        int k=log2(r-l+1);
        cout << max(st[l][k],st[r-(1<<k)+1][k]) << endl;
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章