【POJ 3264】线段树维护区间最值

1.题目链接。题意就是给你一个序列,完后Q组询问 ,每次询问(l,r)区间内最大值和最小值之差。RMQ其实可以很简单的解决,不过最近在复习线段树,就用线段树写一下。


#include
#include
#include
#include
using namespace std;
const int  N = 1e5 + 10;
const int INF = 1e9;
int a[N];
#pragma warning(disable:4996)
int ans_x, ans_y;
struct node
{
	int l, r;
	int minn, mmax;
}s[N<<2];
void build(int l, int r, int n)
{

	s[n].l = l;
	s[n].r = r;
	s[n].minn = INF;
	s[n].mmax = 0;
	if (l == r)
	{
		s[n].mmax = s[n].minn = a[l];
		return;
	}
	int mid = (l + r) >> 1;
	build(l, mid, n << 1);
	build(mid + 1, r, n << 1 | 1);
	s[n].mmax = max(s[n << 1].mmax, s[n << 1 | 1].mmax);
	s[n].minn = min(s[n << 1].minn, s[n << 1 | 1].minn);
}
void query(int l, int r, int n)
{
	if (s[n].l == l && s[n].r == r)
	{
		ans_x = max(ans_x, s[n].mmax);
		ans_y = min(ans_y, s[n].minn);
		return;
	}
	int mid = (s[n].l + s[n].r) >> 1;
	if (r <= mid)
		query(l, r, n << 1);
	else if (l > mid)
		query(l, r, n << 1 | 1);
	else
	{
		query(l, mid, n <<1);
		query(mid + 1, r, n<<1 | 1);
	}
}
int main()
{
	int m, q;
	while (~scanf("%d%d", &m, &q))
	{
		for (int i = 1; i <= m; i++)
			scanf("%d", &a[i]);
		build(1, m, 1);
		while (q--)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			ans_x = 0;
			ans_y = INF;
			query(x, y, 1);
			cout << ans_x-ans_y << endl;
		}
	}
}

 

你可能感兴趣的:(数据结构与算法基于c++实现)