Files
python/TangDou/AcWing/SegmentTree/ZKW/Cogs58.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

107 lines
2.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
延绵的山峰
★★☆ 输入文件:climb.in 输出文件:climb.out 简单对比
时间限制:1 s 内存限制:512 MB
问题描述
有一座延绵不断、跌宕起伏的山,最低处海拔为0,最高处海拔不超过8848米,从这座山的一端走到另一端的过程中,
每走1米海拔就升高或降低1米。有Q个登山队计划在这座山的不同区段登山,当他们攀到各自区段的最高峰时,就会插上队旗。
请你写一个程序找出他们插旗的高度。
输入文件
第1行,一个整数N(N<=10^6),表示山两端的跨度。
接下来N+1行,每行一个非负整数Hi,表示该位置的海拔高度,其中H0=Hn=0。
然后是一个正整数Q(Q<=7000),表示登山队的数量。
接下来Q行,每行两个数Ai, Bi,表示第i个登山队攀爬的区段[Ai,Bi],其中0<=Ai<=Bi<=N。
输出文件
Q行,每行为一个整数,表示第i个登山队插旗的高度。
样例输入
10
0
1
2
3
2
3
4
3
2
1
0
5
0 10
2 4
3 7
7 9
8 8
样例输出
4
3
4
3
2
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100010;
// 快读
int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
int d[N << 2], m;
//构建zkw线段树
void build(int n) {
for (m = 1; m < n;) m <<= 1; // 强行开够(大于n)方便二进制访问叶节点
for (int i = 1; i <= n; i++) d[m + i] = read(); //对zkw的叶子节点赋值
for (int i = m; i; i--) d[i] = max(d[i << 1], d[i << 1 | 1]); //待所有叶子节点有值后,统一执行一次向上数据统计信息汇总
}
//区间查询最大值
int query(int l, int r) {
int ans = 0;
for (l = l + m - 1, r = r + m + 1; l ^ r ^ 1; l >>= 1, r >>= 1) {
if (~l & 1) ans = max(d[l ^ 1], ans);
if (r & 1) ans = max(d[r ^ 1], ans);
}
return ans;
}
int main() {
//文件输入输出
#ifndef ONLINE_JUDGE
freopen("Cogs58.in", "r", stdin);
#endif
int n, q, l, r;
/*
第1行,一个整数N(N<=10^6),表示山两端的跨度。
接下来N+1行,每行一个非负整数Hi,表示该位置的海拔高度,其中H0=Hn=0。
*/
n = read(), n++; // H0~Hn 共n+1行,而且,题目告诉我们H0=Hn=0,会在输入数据时给出,所以,一共是n+1点
//构建
build(n);
q = read();
for (int i = 1; i <= q; i++) {
l = read(), r = read();
printf("%d\n", query(l + 1, r + 1));
}
return 0;
}