题目链接:点击这里
数据有点水,可以练习一下线段树
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const int MOD = 10000007;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int maxn = 100010;
inline int lc(int p) {return p<<1;} //左孩子
inline int rc(int p) {return p<<1|1;} //右孩子
struct Node {
int l, r; //左右区间
int maxx; //区间最值
}tree[4*maxn];
int n, m, x, y, a[maxn];
int resMax;
void pushUp(int i) //维护子节点
{
tree[i].maxx = max(tree[lc(i)].maxx, tree[rc(i)].maxx);
}
void build(int i, int l, int r)
{
tree[i].l = l;
tree[i].r = r;
if(l==r) //叶结点
{
tree[i].maxx = a[l];
return;
}
int mid = (l + r)>>1;
build(lc(i), l, mid);
build(rc(i), mid+1, r);
pushUp(i); //回溯,维护子节点
}
void query(int i, int ql, int qr)
{
if(ql<=tree[i].l && tree[i].r<=qr)
{
resMax = max(resMax, tree[i].maxx);
return;
}
int mid = (tree[i].l + tree[i].r) >> 1;
if(ql<=mid)
query(lc(i), ql, qr);
if(qr>mid)
query(rc(i), ql, qr);
pushUp(i);
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
build(1, 1, n); //建树
while(m--)
{
scanf("%d%d", &x, &y);
resMax = -INF;
query(1, x, y); //查询
printf("%d\n", resMax);
}
return 0;
}
菜是原罪QAQ
发布了723 篇原创文章 · 获赞 105 · 访问量 11万+
关注