题目链接:http://poj.org/problem?id=3264
题目大意:
一个农夫有N头牛,每头牛的高度不同,我们需要找出最高的牛和最低的牛的高度差。
解题思路:经典 RMQ
#include <iostream> #include<cstdio> #include<cmath> #include<algorithm> using namespace std; #define rep(i,a,b) for(int i=a;i<=b;i++) int n,q,l,r; int a[50005]; int maxx[50005][25],minn[50005][25]; void RMQ() { rep(j,1,20) rep(i,1,n) if(i + (1 << j)-1<=n) { maxx[i][j] = max(maxx[i][j-1], maxx[i + (1 << (j - 1))][j - 1]); minn[i][j] = min(minn[i][j-1], minn[i + (1 << (j - 1))][j - 1]); } } int main() { while(~scanf("%d%d",&n,&q)) { rep(i,1,n) { scanf("%d",&a[i]); maxx[i][0]=minn[i][0]=a[i]; } RMQ(); rep(i,1,q) { scanf("%d%d",&l,&r); int k=(int)(log(r-l+1.0)/log(2.0)); int maxnum = max(maxx[l][k], maxx[r - (1 << k) +1][k]); int minnum = min(minn[l][k], minn[r - (1 << k) +1][k]); //printf("%d %d\n",maxnum,minnum); printf("%d\n", maxnum - minnum); } } return 0; }