Balanced Lineup(区间最值差)

POJ 3264

题意:给定序列,求区间 [x,y] 最大值和最小值的差

标签:区间最值

分析:线段树维护区间最大最小值,分开查询。
还是老问题,POJ流同步关了还是T

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const int mod=1e9+7;
const int maxn=5e4+10;

struct node {
	int l,r,k,Max,Min;
} tree[maxn<<2];
int n,m;
int a[maxn];

void push_up(int p){
	//tree[p].k=tree[p<<1].k+tree[(p<<1)|1].k;
	tree[p].Max=max(tree[p<<1].Max,tree[(p<<1)|1].Max);
	tree[p].Min=min(tree[p<<1].Min,tree[(p<<1)|1].Min);
}

void build(int p, int l, int r) {
	tree[p].l=l;
	tree[p].r=r;
	if (l==r) {
		tree[p].Max=tree[p].Min=a[l];
		return;
	}
	int m=(l+r)>>1;
	build(p<<1,l,m),build((p<<1)|1,m+1,r);
	push_up(p);
}

int queryMin(int p, int x, int y) {
	if (x<=tree[p].l && y>=tree[p].r) return tree[p].Min;
	//push_down(p);
	int m=(tree[p].l+tree[p].r)>>1;
	int ans=INF;
	if (x<=m) ans=min(ans,queryMin(p<<1,x,y));
	if (y>m) ans=min(ans,queryMin((p<<1)|1,x,y));
	return ans;
}

int queryMax(int p, int x, int y) {
	if (x<=tree[p].l && y>=tree[p].r) return tree[p].Max;
	//push_down(p);
	int m=(tree[p].l+tree[p].r)>>1;
	int ans=0;
	if (x<=m) ans=max(ans,queryMax(p<<1,x,y));
	if (y>m) ans=max(ans,queryMax((p<<1)|1,x,y));
	return ans;
}

int main() {

	//ios::sync_with_stdio(0);
	//cin.tie(0);
	//cout.tie(0);
	scanf("%d%d",&n,&m);
	for (int i=1; i<=n; i++) scanf("%d",&a[i]);
	build(1,1,n);
	int x,y;
	while (m--){
		scanf("%d%d",&x,&y);
		printf("%d\n",queryMax(1,x,y)-queryMin(1,x,y));
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值