poj 3264 Balanced Lineup(线段树)

传送门

题意:
求任意区间最大值以及最小值的差

#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll int
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll INFF = 2000000;
struct node {
	ll maxn, minn,begin,end;
}tree[200000];
void BuildTree(ll flag,ll begin,ll end) {
	tree[flag].maxn = -INFF;
	tree[flag].minn = INFF;
	tree[flag].begin = begin;
	tree[flag].end = end;
	if (begin != end) {
		BuildTree(flag * 2, begin, (begin + end) / 2);
		BuildTree(flag * 2 + 1, (begin + end) / 2 + 1, end);
	}
}//建树
void Insert(ll flag, ll set, ll value) {
	if (tree[flag].begin == tree[flag].end) {
		tree[flag].maxn = tree[flag].minn = value;
		return;
	}
	if (set <= (tree[flag].begin + tree[flag].end) / 2) {
		Insert(flag * 2, set, value);
	}
	else {
		Insert(flag * 2 + 1, set, value);
	}
	//更新最大值以及最小值
	tree[flag].maxn = max(tree[flag * 2].maxn, tree[flag].maxn);
	tree[flag].maxn = max(tree[flag * 2 + 1].maxn, tree[flag].maxn);
	tree[flag].minn = min(tree[flag * 2].minn, tree[flag].minn);
	tree[flag].minn = min(tree[flag * 2 + 1].minn, tree[flag].minn);
	return;
}
ll maxv, minv;
void Query(ll flag,ll begin,ll end) {
	//剪枝,已经找到最大值以及最小值,即无序更新跳出就行
	if (maxv >= tree[flag].maxn && minv <= tree[flag].minn)return;
	if (tree[flag].begin == begin && tree[flag].end == end) {
	//	cout << flag << endl;
		maxv = max(maxv, tree[flag].maxn);
		minv = min(minv, tree[flag].minn);
		return;
	}
	ll mid = (tree[flag].begin + tree[flag].end)/2;
	if (end <= mid) {
		Query(flag * 2, begin, end);
	}
	else if (begin > mid) {
		Query(flag * 2 + 1, begin, end);
	}
	else {
		Query(flag * 2, begin, mid);
		Query(flag * 2 + 1, mid + 1, end);
	}
}
int main() {
	FAST_IO;
	ll n, m, k, i, j, vb;
	while (cin >> n >> m) {
		BuildTree(1, 1, n);
		for (i = 1; i <= n; i++) {
			cin >> j;
			Insert(1, i, j);
		}
		//for (i = 1; i <= n; i++) cout << i << ":" << tree[i].begin << " " << tree[i].end << " " << tree[i].maxn << " " << tree[i].minn << endl;
		ll x, y;
		for (i = 0; i < m; i++) {
			cin >> x >> y;
			maxv = -INFF;
			minv = INFF;
			Query(1, x, y);
			//cout << maxv << " " << minv << endl;
			ll result = maxv - minv;
			cout << result << endl;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GUESSERR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值