| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 29631 | Accepted: 13970 | |
| Case Time Limit: 2000MS | ||
Description
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.
Input
Lines 2..N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2..N+Q+1: Two integers A and B (1 ≤A ≤ B ≤ N), representing the range of cows from A toB inclusive.
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
题意:给出n个数,有Q个询问,每个询问a,b要求得出区间[a,b]的最大值与最小值之差。
思路:这里用了RMQ的ST算法。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdlib> #define L(rt) (rt<<1) #define R(rt) (rt<<1|1) #define ll long long #define eps 1e-6 using namespace std; const int maxn=50005; int A[maxn],rmq_max[maxn][16],rmq_min[maxn][16]; int n,m; void initRMQ() { for(int i=1;i<=n;i++) rmq_max[i][0]=rmq_min[i][0]=A[i]; for(int k=1;(1<<k)<=n;k++) for(int i=1;i+(1<<k)-1<=n;i++) { rmq_max[i][k]=max(rmq_max[i][k-1],rmq_max[i+(1<<(k-1))][k-1]); rmq_min[i][k]=min(rmq_min[i][k-1],rmq_min[i+(1<<(k-1))][k-1]); } } int RMQ(int a,int b) { int k=log(b-a+1.0)/log(2.0); int x=max(rmq_max[a][k],rmq_max[b-(1<<k)+1][k]); int y=min(rmq_min[a][k],rmq_min[b-(1<<k)+1][k]); return x-y; } int main() { int a,b; while(~scanf("%d%d",&n,&m)) { for(int i=1;i<=n;i++) scanf("%d",&A[i]); initRMQ(); while(m--) { scanf("%d%d",&a,&b); printf("%d\n",RMQ(a,b)); } } return 0; }

本文介绍了一种使用ST算法解决区间最大值与最小值查询问题的方法,适用于固定区间内的快速查询需求。通过预处理构建表格,实现高效求解指定范围内元素的最大值与最小值之差。
308

被折叠的 条评论
为什么被折叠?



