Maximum value of sequence interval
acwing 1270
Time limit:2s
Memory limit:64MB
Problem Description
Enter a string of numbers and give you M queries. Each query will give you two numbers X, Y asks you to say the maximum number in the interval from X to Y.
Input
-
The two integers N and M in the first line represent the number of digits and the number of queries;
The next row is N numbers;
The next M lines, each line has two integers X, Y.
1≤N≤10 5
1≤M≤10 6
1≤X≤Y≤N No
number in the sequence exceeds 2 31 −1
Output
There are a total of M lines of output, and each line outputs a number.
Sample Input
10 2
3 2 4 5 6 8 1 2 9 7
1 4
3 8
Sample Output
5
8
Line segment tree solution
AC code:
#include<cstdio>
#include<iostream>
using namespace std;
int n,m,x[100005]; //原数组
struct Node{
int l,r,w; //线段树的左、右、值
};
Node tree[400005]; //线段树
void build(int num,int l,int r){
if(l == r){
//相等说明已经到了叶子节点
tree[num].l = l,tree[num].r = r,tree[num].w = x[l];return;
}
int mid = (l + r) >> 1;
int lc = num << 1; //乘2是左子树
int rc = num << 1 | 1; //乘2或1是右子树
build(lc,l,mid); //建左子树
build(rc,mid + 1,r); //建右子树
tree[num].l = l,tree[num].r = r,tree[num].w = max(tree[lc].w,tree[rc].w);return; //保存左右子树的最大子(区间最大)
}
int find(int num,int l,int r){
if(tree[num].l == l && tree[num].r == r)
return tree[num].w; //找到目标区间
int mid = (tree[num].l + tree[num].r) >> 1;
int lc = num << 1;
int rc = num << 1 | 1;
if(l > mid)
return find(rc,l,r); //继续在右子树找
else if(r <= mid)
return find(lc,l,r); //继续在左子树找
else return max(find(lc,l,mid),find(rc,mid + 1,r)); //左子树找一段,右子树找一段
}
int main(){
scanf("%d %d",&n,&m);
for(int i = 1;i <= n;++i)
scanf("%d",x + i);
build(1,1,n);
while(m--){
int l,r;
scanf("%d %d",&l,&r);
printf("%d\n",find(1,l,r));
}
return 0;
}