POJ3264 Balanced Lineup

/*Interval Tree*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>

using namespace std;

struct node {
	int l, r;
	int MIN, MAX, num;
};

const int maxn = 500010;
const int INF = 100000000;

node tree[maxn << 2];
int n, q;
int Min, Max;


void solve(int root)
{
	tree[root].MIN = min(tree[root << 1].MIN, tree[root << 1 | 1].MIN);
	tree[root].MAX = max(tree[root << 1].MAX, tree[root << 1 | 1].MAX);
}

void build(int l, int r, int root)
{
	tree[root].l = l;
	tree[root].r = r;

	if (tree[root].l == tree[root].r) {
		scanf("%d", &tree[root].num);
		tree[root].MIN = tree[root].MAX = tree[root].num;
		return;
	}

	int mid = (l + r) >> 1;
	build(l, mid, root << 1);
	build(mid + 1, r, root << 1 | 1);
	solve(root);
}

void query(int l, int r, int root)
{
	if (tree[root].l >= l && tree[root].r <= r) {
		Min = min(Min, tree[root].MIN);
		Max = max(Max, tree[root].MAX);
		return;
	}

	int mid = (tree[root].l + tree[root].r) >> 1;
	if (r <= mid)
		query(l, r, root << 1);
	else if (l > mid)
		query(l, r, root << 1 | 1);
	else {
		query(l, mid, root << 1);
		query(mid + 1, r, root << 1 | 1);
	}
}

int main()
{
	while (cin >> n >> q) {
		build(1, n, 1);
		int l, r;
		for (int i = 0; i < q; ++i) {
			scanf("%d%d", &l, &r);
			Min = INF; Max = -INF;
			query(l, r, 1);
			cout << Max - Min << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值