题目:
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.
https://www.luogu.com.cn/problem/P2880
题意!:
给你一个长度为n的序列,有m次询问,每次询问一个区间内的最大值与最小值的差。
思路:
求区间最值问题,可以使用线段数求解,也可以ST表直接求解区间最值。这里给出用ST表求解的代码(几乎是模板题,其他题皆可稍加改动进行使用)
代码:
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
const double N = 1e6+10;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const inline int read(){
int k = 0, f = 1; char c = getchar();
for(;!isdigit(c); c = getchar())
if(c == '-') f = -1;
for(;isdigit(c); c = getchar())
k = k * 10 + c - '0';
return k * f;
}
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define MAXN 500010
int lxy[MAXN][22];//最大值
int hrb[MAXN][22];//最小值
int n , m , i , j , k , l , r;
int ST(int l , int r)
{
int s = log2(r-l+1) , x , y;
x = max(lxy[l][s],lxy[r-(1<<s)+1][s]);
y = min(hrb[l][s],hrb[r-(1<<s)+1][s]);
return x-y;
}
int main()
{
scanf("%d%d",&n,&m);
for(i = 1 ; i <= n ; i++)
{
scanf("%d",&lxy[i][0]);
hrb[i][0] = lxy[i][0];
}
for(i = 1 ; i <= 21 ; i++)
{
for(k = 1 ; k+(1<<i)<=n+1 ; k++)
{
lxy[k][i] = max(lxy[k][i-1],lxy[k+(1<<(i-1))][i-1]);
hrb[k][i] = min(hrb[k][i-1],hrb[k+(1<<(i-1))][i-1]);
}
}
for(i = 1 ; i <= m ; i++)
{
scanf("%d%d",&l,&r);
printf("%d\n",ST(l,r));
}
return 0;
}