题目描述
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 ≤ 180,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.
输入格式
Line 1: Two space-separated integers, N and Q.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.
输出格式
Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.
题意:给定牛的高度,求区间中最高的牛减去最低的牛
在静态数据中,在查询速度最快的是O(1)用ST算法,倍增思想;
定义 dp[s][k] = min{dp[s][k-1],dp[s+1<<(k-1)][k-1]}
其中,1<<(k-1)表示 2^k-1;
查询时要注意区间[L,R]的长度为len = R - L + 1。两个查询区间的长度为x。x <= len && 2x>=len时,这要保证能覆盖。
下面介绍一下取对数log2 在库函数中可以调用:
int k=(int)(log(double(R-L+1)) / log(2.0)); //换底公式 以10为底
int k=log2(R-L+1);
下面是手动的记录的;
LOG2[0] = -1;
for(int i =1;i<=N;i++){
LOG2[i] = LOG2[i>>1] + 1;
}
下面是这道题的AC代码
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int N = 50005;
int n, m;
int a[N], dp_max[N][22], dp_min[N][22];
int LOG2[N];
void st_init() {
//LOG2[0] = -1;
//for (int i = 1; i <= N; i++) LOG2[i] = LOG2[i >> 1] + 1;
for (int i = 1; i <= n; i++) {
dp_max[i][0] = a[i];
dp_min[i][0] = a[i];
}
int p = (int)(log(double(n)) / log(2.0));
for (int k = 1; k <= p; k++) {//倍增计算小区间,在算大区间
for (int s = 1; s + (1 << k) <= n + 1; s++) {
dp_max[s][k] = max(dp_max[s][k - 1], dp_max[s + (1 << (k - 1))][k - 1]);
dp_min[s][k] = min(dp_min[s][k - 1], dp_min[s + (1 << (k - 1))][k - 1]);
}
}
}
int st_query(int L, int R) {
int k = (int)(log(double(R - L + 1)) / log(2.0));
int x = max(dp_max[L][k], dp_max[R - (1 << k) + 1][k]);
int y = min(dp_min[L][k], dp_min[R - (1 << k) + 1][k]);
return x - y;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
st_init();
for (int i = 1; i <= m; i++) {
int L, R;
cin >> L >> R;
printf("%d\n", st_query(L, R));
}
return 0;
}