51node1174: 区间中最大的数(线段树)

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
收藏
关注
给出一个有N个数的序列,编号0 - N - 1。进行Q次查询,查询编号i至j的所有数中,最大的数是多少。
例如: 1 7 6 3 1。i = 1, j = 3,对应的数为7 6 3,最大的数为7。(该问题也被称为RMQ问题)
Input
第1行:1个数N,表示序列的长度。(2 <= N <= 10000)
第2 - N + 1行:每行1个数,对应序列中的元素。(0 <= S[i] <= 10^9)
第N + 2行:1个数Q,表示查询的数量。(2 <= Q <= 10000)
第N + 3 - N + Q + 2行:每行2个数,对应查询的起始编号i和结束编号j。(0 <= i <= j <= N - 1)
Output
共Q行,对应每一个查询区间的最大值。
Input示例
5
1
7
6
3
1
3
0 1
1 3
3 4
Output示例
7
7
3
分析:线段树入门题
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int d[40000],n=1;//线段树一般开到4倍的叶子结点,此n是完美二叉树的节点数 
void update(int k,int num)//更新第k个数为num
{
	k=k+n-1;
	d[k]=num;//最低层
	while(k>0){//更新父节点  
		k=(k-1)/2;
		d[k]=max(d[2*k+1],d[2*k+2]);
	}
}
int query(int a,int b,int k,int l,int r)//查询a和b范围内的区间最大值  
{
	if(b<=l||a>=r) return -1;
	if(a<=l&&b>=r) return d[k];
	return max(query(a,b,k*2+1,l,(l+r)/2),query(a,b,k*2+2,(l+r)/2,r));
}
int main()
{
	int c,num,a,b,m;
	cin>>c;
	while(n<c)n=n*2;
	memset(d,-1,sizeof(d));
	for(int i=0;i<c;i++){
		cin>>num;
		update(i,num);		
	}
	cin>>m;
	for(int i=0;i<m;i++){
		cin>>a>>b;
		cout<<query(a,b+1,0,0,n)<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zpjlkjxy/article/details/80729659