欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU 5443 The Water Problem (线段树)

程序员文章站 2022-05-11 18:08:37
...

题意:给出n个数字,q个查询,查询l~r中最大的数。

题解:线段树

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int maxn = 1111;
int t, n, q, a[maxn], l, r;
struct node {
	int val;
};
struct ST {
	node tree[maxn << 2];
	void build(int l, int r, int rt) {
		if (l == r) {
			tree[rt].val = a[l];
		}
		else {
			int mid = (l + r) >> 1;
			build(l, mid, rt << 1);
			build(mid + 1, r, rt << 1 | 1);
			tree[rt].val = max(tree[rt << 1].val, tree[rt << 1 | 1].val);
		}
	}
	int query(int l, int r, int L, int R, int rt) {    //L R 为查询区间
		if (L <= l && r <= R) {  //单点查询 l == r
			return tree[rt].val;
		}
		int mid = (l + r) >> 1;
		int ans1 = 0;
		if (L <= mid) {
			ans1 = query(l, mid, L, R, rt << 1);
		}
		if (R > mid) {
			ans1 = max(ans1, query(mid + 1, r, L, R, rt << 1 | 1));
		}
		return ans1;
	}
}stree;

int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);
		for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
		stree.build(1, n, 1);
		scanf("%d", &q);
		while (q--) {
			scanf("%d%d", &l, &r);
			printf("%d\n", stree.query(1, n, l, r, 1));
		}
	}
	return 0;
}