【清北前紧急补课1】rmq
?
poj3264 balanced lineup
題目描述
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.
輸入輸出格式
輸入格式:
?
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.
?
?
主要還是要用rmq(雖然有人告訴我用貪心模擬可我覺得一定會爆
?
rmq就是在一個區間里找最小值或最大值 用st的做法
理解一下rmq的原理:假設我們要查詢的這個數值在區間a[i]中,那么我們用f[i][j]來表示這個數;具體含義是這樣的:f[i][j]表示 從i開始的2^j個數中的最大值 那么就可以確定a[i]=f[i][0];
那么對于一個2^j的數列我們可以把他平均分成兩段 每段的長度為2^j-1;第一段是i到i+2^j-1 -1;第二段是i+2^j-1到i+2^j-1;
可以分別表示為:f[i][j-1] ?f[i+2^j-1][j-1]
則設有2^k=j-i+1(即一個從i到j的區間的長度)那么有rmq(i,j)=max(f[i][k],f[j-2^k+1][k]);(區間最大值 最小值同理
?
則可以得出這個題的程序:
#include<iostream> #include<algorithm> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; int n,q,s,e,maxn,minn; int f1[200001][51],f2[200001][51],a[200001];int rmq(int i,int j){int k=0;while((1<<(k+1))+i<=j+1) k++;minn=min(f2[i][k],f2[j-(1<<k)+1][k]);maxn=max(f1[i][k],f1[j-(1<<k)+1][k]);return maxn-minn; }int main(){scanf("%d%d",&n,&q);for(int i=1;i<=n;i++) cin>>a[i];for(int i=1;i<=n;i++){f1[i][0]=f2[i][0]=a[i];}for(int j=1;(1<<j)<=n;j++)for(int i=1;i+(1<<j)<=n+1;i++){f1[i][j]=max(f1[i][j-1],f1[(1<<(j-1))+i][j-1]);f2[i][j]=min(f2[i][j-1],f2[(1<<(j-1))+i][j-1]);}for(int i=1;i<=q;i++){scanf("%d%d",&s,&e);cout<<rmq(s,e)<<endl;} return 0; }豈不nice
?
關于st表的k的另一種求法
for (int a=1;(1<<a)<=n;a++)er[(1<<a)]=a;for (int a=3;a<=n;a++)if (er[a]==0) er[a]=er[a-1];?
再另建一個函數
int query(int l,int r) {int k=er[r-l+1];return max(f[l][k],f[r-(1<<k)+1][k]); }?
轉載于:https://www.cnblogs.com/civilization-ga/p/9318601.html
總結
以上是生活随笔為你收集整理的【清北前紧急补课1】rmq的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 波利王超级蔓越莓一般要吃多久?
- 下一篇: 郴州市乌米香姐粽子店地址电话?