POJ - 3264
For the daily milking, Farmer John’s N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.
Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.
n头牛,给出每头牛的高度,q次询问,求每次l到r区间的最高牛与最低牛的高度差
做法很多,简单题目
st表写法:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int maxn = 50000 + 4;
int st[maxn][20][3];
void Build(int n) {
for(int j = 1; j < 20; ++j) {
for(int i = 1; i + (1 << (j - 1)) <= n; ++i) {
st[i][j][0] = min(st[i][j - 1][0], st[i + (1 << (j - 1))][j - 1][0]);
st[i][j][1] = max(st[i][j - 1][1], st[i + (1 << (j - 1))][j - 1][1]);
}
}
}
int Query(int l, int r) {
int len = int(log((double)(r - l + 1)) / log(2.0));
int minn = min(st[l][len][0], st[r - (1 << len) + 1][len][0]);
int maxx = max(st[l][len][1], st[r - (1 << len) + 1][len][1]);
return maxx - minn;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
for(int i = 1; i <= n; ++i) {
cin >> st[i][0][0];
st[i][0][1] = st[i][0][0];
}
Build(n);
while(q--) {
int l, r;
cin >> l >> r;
if(l == r) cout << 0 << endl;
else cout << Query(l, r) << endl;
}
}