今天终于把RMQ学了,st算法
入门题目
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 17371 | Accepted: 8044 | |
Case TimeLimit: 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 Johndecides to organize a game of Ultimate Frisbee with some of thecows. To keep things simple, he will take a contiguous range ofcows from the milking lineup to play the game. However, for all thecows 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 thedifference in height between the shortest and the tallest cow inthe group.
Input
Lines 2.. N+1: Line i+1 contains a single integer thatis the height of cow i
Lines N+2.. N+ Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing therange of cows from A to B inclusive.
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
POJ不能用log2,不知道为什么,于是手打了一个,应该还快点。
inline long log2(long a)
{
long ans = 0;
while (a>>=1){ans++;}
return ans;
}
#include <iostream>
//#include <cmath>
using std::cout;
using std::cin;
#define Max(a,b) (a>b?a:b)
#define Min(a,b) (a<b?a:b)
long n;long q;
long f[50010][20];
long f2[50010][20];
inline long log2(long a)
{
long ans = 0;
while (a>>=1){ans++;}
return ans;
}
long gmax(long l,long r)
{
long k = long(log2(r-l+1));
return Max(f[l][k],f[r-(1<<k)+1][k]);
}
long gmin(long l,long r)
{
long k = long(log2(r-l+1));
return Min(f2[l][k],f2[r-(1<<k)+1][k]);
}
int main()
{
scanf("%ld%ld",&n,&q);
for (long i=1;i<n+1;i++)
{
long h;
scanf("%ld",&h);
f[i][0] = h;
f2[i][0] = h;
}
for (long j=1;(1<<j)<=n;j++)
for (long i=1;i<=n-(1<<j)+1;i++)
{
f[i][j] = Max(f[i][j-1],f[i+(1<<(j-1))][j-1]);
f2[i][j] = Min(f2[i][j-1],f2[i+(1<<(j-1))][j-1]);
}
for (long i=1;i<q+1;i++)
{
long a;long b;
scanf("%ld%ld",&a,&b);
printf("%ld\n",gmax(a,b)-gmin(a,b));
}
return 0;
}