1174 区间中最大的数
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
例如: 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
题意
输出q组查询的最大值。
解题思路
线段树裸题。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10005;int tree[maxn<<2],arr[maxn];
void pushup(int rt)
{tree[rt]=max(tree[rt<<1],tree[rt<<1|1]);
}
void biud(int l,int r,int rt)
{if(l==r){tree[rt]=arr[l];return;}int m=(l+r)>>1;biud(l,m,rt<<1);biud(m+1,r,rt<<1|1);pushup(rt);
}
int query(int L,int R,int l,int r,int rt){if(L <= l && r <= R){return tree[rt];}int m=(l+r)>>1;int ans=0;if(L <= m) ans=max(ans,query(L,R,l,m,rt<<1));if(R > m) ans=max(ans,query(L,R,m+1,r,rt<<1|1));return ans;
}
int main()
{
// freopen("in.txt","r",stdin);int n;scanf("%d",&n);for(int i=0; i<n; i++)scanf("%d",&arr[i]);biud(0,n-1,1);int q;scanf("%d",&q);for(int i=0; i<q; i++){int l,r;scanf("%d%d",&l,&r);printf("%d\n",query(l,r,0,n-1,1));}return 0;
}