poj3264_Balanced Lineup_线段树

//poj3264 Balanced Lineup
//线段树

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 50010;
struct MinMax{
	int min, max;
};
struct Node{
	struct MinMax minmax;
	int left, right;
}tree[MAXN * 3];
int arrCow[MAXN];
int nN, nM;
inline int Min(int x, int y){
	return x < y ? x : y;
}
inline int Max(int x, int y){
	return x > y ? x : y;
}
void build(int root, int left, int right){
	tree[root].left = left;
	tree[root].right = right;
	if(left == right) tree[root].minmax.max = tree[root].minmax.min = arrCow[left];
	else{
		int mid = (left + right) >> 1;
		build(root * 2, left, mid);
		build(root * 2 + 1, mid + 1, right);
		tree[root].minmax.min = Min(tree[root * 2].minmax.min, tree[root * 2 + 1].minmax.min);
		tree[root].minmax.max = Max(tree[root * 2].minmax.max, tree[root * 2 + 1].minmax.max);
	}
}
struct MinMax search(int root, int left, int right){
	if(tree[root].left == left && tree[root].right == right)
		return tree[root].minmax;
	int mid = (tree[root].left + tree[root].right) >> 1;
	if(mid >= right)
		return search(root * 2, left, right);
	else if(mid < left)
		return search(root * 2 + 1, left, right);
	else{
		struct MinMax tmp1, tmp2, tmp3;
		tmp1 = search(root * 2, left, mid);
		tmp2 = search(root * 2 + 1, mid + 1, right);
		tmp3.min = Min(tmp1.min, tmp2.min);
		tmp3.max = Max(tmp1.max, tmp2.max);
		return tmp3;
	}
}
int main(){
	while(cin >> nN >> nM){
		memset(tree, 0, sizeof(tree));
		memset(arrCow, 0, sizeof(arrCow));
		for(int i = 1; i <= nN; i++)
			scanf("%d", arrCow + i);
		build(1, 1, nN);
		for(int i = 1; i <= nM; i++){
			int nL, nR;
			scanf("%d %d", &nL, &nR);
			struct MinMax tmp = search(1, nL, nR);
			cout << tmp.max - tmp.min << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值