题目:
1270. 数列区间最大值 - AcWing题库
输入样例:
10 2
3 2 4 5 6 8 1 2 9 7
1 4
3 8
输出样例:
5
8
代码:
#include <cstdio>
#include <iostream>
#include <climits>//INT_MIN头文件using namespace std;const int N = 100010;int n, m;
int w[N];//一维数组储存输入数据//定义线段树结点
struct Node
{int l, r;int maxv;
}tr[N * 4];//l、r表示系结点区间范围。maxv表示区间最大值//又左右儿子得结点u最大值
void pushup(int u)
{tr[u].maxv=max(tr[u<<1].maxv,tr[u<<1|1].maxv);
}//初始化线段树各个结点
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].maxv;//查找区间包含结点区间int mid = tr[u].l + tr[u].r >> 1;int maxv = INT_MIN;if (l <= mid) maxv = query(u << 1, l, r);//查找区间与该结点u的左儿子有交集if (r > mid) maxv = max(maxv, query(u << 1 | 1, l, r));//查找区间与该结点u的右儿子有交集return maxv;
}int main()
{scanf("%d%d", &n, &m);for (int i = 1; i <= n; i ++ ) scanf("%d", &w[i]);build(1, 1, n);//初始化线段树各个结点int l, r;while (m -- ){scanf("%d%d", &l, &r);printf("%d\n", query(1, l, r));}return 0;
}