传送门
题意:
求任意区间最大值以及最小值的差
#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;
}
}
}