1270. The maximum value of the sequence interval

Insert picture description here
Idea:
According to the idea of ​​the line segment tree, another number of the line segment tree can be represented by maxn, and each time it is updated, the maximum value of the left and right sons covers the maximum value
code:

# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

const int N = 100010;
int w[N];
int n,m;

struct node
{
    
    
    int l,r;
    int maxn;
}tr[4 * N];

void pushup(int u)
{
    
    
    tr[u].maxn = max(tr[u << 1].maxn,tr[u << 1 | 1].maxn);
}

void build(int u,int l,int r)
{
    
    
    if(l == r)
    tr[u] = {
    
    l,r,w[r]};
    else
    {
    
    
        tr[u] = {
    
    l,r};
        int mid = l + r >> 1;
        build(u << 1,l,mid);
        build(u << 1 | 1,mid + 1,r);
        pushup(u);
    }
}

int query(int u,int l,int r)
{
    
    
    if(tr[u].l >= l && tr[u].r <= r) return tr[u].maxn;
    int mid = tr[u].l + tr[u].r >> 1;
    int maxx = 0;
    if(l <= mid) maxx = max(query(u << 1,l,r),maxx);
    if(r > mid) maxx = max(query(u << 1 | 1,l,r),maxx);
    return maxx;
}

int main()
{
    
    
    int x,y;
    scanf("%d %d",&n,&m);
    for(int i = 1;i <= n;i++)
    {
    
    
        scanf("%d",&w[i]);
    }
    build(1,1,n);
    while(m--)
    {
    
    
        scanf("%d %d",&x,&y);
        printf("%d\n",query(1,x,y));
    }
    
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45812180/article/details/114849450