The Water Problem (10分)
In Land waterless, water is a very limited resource. People always fight for the biggest source of water. Given a sequence of water sources with a1 ,a2 ,a3 ,…,an representing the size of the water source. Given a set of queries each containing 2 integers l and r, please find out the biggest water source between al and ar .
输入格式:
First you are given an integer T (T ≤ 10) indicating the number of test cases. For each test case, there is a number n (0 ≤ n ≤ 1000) on a line representing the number of water sources. n integers follow, respectively a1 ,a2 ,a3 ,…,an , and each integer is in {1,…,10^6 }. On the next line, there is a number q (0 ≤ q ≤ 1000) representing the number of queries. After that, there will be q lines with two integers l and r (1 ≤ l ≤ r ≤ n) indicating the range of which you should find out the biggest water source.
输出格式:
For each query, output an integer representing the size of the biggest water source.
输入样例:
3
1
100
1
1 1
5
1 2 3 4 5
5
1 2
1 3
2 4
3 4
3 5
3
1 999999 1
4
1 1
1 2
2 3
3 3
输出样例:
100
2
3
4
4
5
1
999999
999999
1
解题
该题直接暴力解也行,这里用线段树,二分查找。
代码
#include <algorithm> //7-5 The Water Problem (10分)
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 1e3 + 2;
int d[maxn * 4], num[maxn];
void build(int s, int t, int p) {
if (s == t) {
//对 [s, t] 区间建立线段树, 当前根的编号为 p
d[p] = num[s];
return;
}
int m = (s + t) >> 1;
build(s, m, p * 2); //最终可以求出d[p * 2]
build(m + 1, t, p * 2 + 1); //最终可以求出d[p * 2 + 1]
d[p] = max(d[p * 2], d[p * 2 + 1]);
}
int getMaxValue(int l, int r, int s, int t, int p) {
// 要查询区间 [l ,r] 的最大值
if (l <= s && r >= t) return d[p]; //所求区间包含了已知区间
int m = (s + t) / 2; //二分查找
if (r <= m) {
return getMaxValue(l, r, s, m, p * 2);
} else if (l > m) {
return getMaxValue(l, r, m + 1, t, p * 2 + 1);
} else {
return max(getMaxValue(l, m, s, m, p * 2),
getMaxValue(m + 1, r, m + 1, t, p * 2 + 1));
}
}
int main() {
int T, n, q;
cin >> T;
while (T--) {
// cin >> n;
scanf("%d", &n);
for (int j = 1; j <= n; j++) scanf("%d", &num[j]);
build(1, n, 1); //建立区间最值线段树
cin >> q;
int l, r;
while (q--) {
scanf("%d %d", &l, &r);
cout << getMaxValue(l, r, 1, n, 1) << endl; //二分查找
}
}
system("pause");
return 0;
}
有关线段树:https://blog.csdn.net/qq_45349225/article/details/109338072
详细介绍:https://oi-wiki.org/ds/seg/