【bzoj3831】[Poi2014]Little Bird 单调队列优化dp

时间:2023-01-20 08:42:17

原文地址:http://www.cnblogs.com/GXZlegend/p/6826475.html


题目描述

In the Byteotian Line Forest there are   trees in a row. On top of the first one, there is a little bird who would like to fly over to the top of the last tree. Being in fact very little, the bird might lack the strength to fly there without any stop. If the bird is sitting on top of the tree no.  , then in a single flight leg it can fly to any of the trees no.i+1,i+2…I+K, and then has to rest afterward.
Moreover, flying up is far harder to flying down. A flight leg is tiresome if it ends in a tree at least as high as the one where is started. Otherwise the flight leg is not tiresome.
The goal is to select the trees on which the little bird will land so that the overall flight is least tiresome, i.e., it has the minimum number of tiresome legs. We note that birds are social creatures, and our bird has a few bird-friends who would also like to get from the first tree to the last one. The stamina of all the birds varies, so the bird's friends may have different values of the parameter  . Help all the birds, little and big!
有一排n棵树,第i棵树的高度是Di。
MHY要从第一棵树到第n棵树去找他的妹子玩。
如果MHY在第i棵树,那么他可以跳到第i+1,i+2,...,i+k棵树。
如果MHY跳到一棵不矮于当前树的树,那么他的劳累值会+1,否则不会。
为了有体力和妹子玩,MHY要最小化劳累值。

输入

There is a single integer N(2<=N<=1 000 000) in the first line of the standard input: the number of trees in the Byteotian Line Forest. The second line of input holds   integers D1,D2…Dn(1<=Di<=10^9) separated by single spaces: Di is the height of the i-th tree.
The third line of the input holds a single integer Q(1<=Q<=25): the number of birds whose flights need to be planned. The following Q lines describe these birds: in the i-th of these lines, there is an integer Ki(1<=Ki<=N-1) specifying the i-th bird's stamina. In other words, the maximum number of trees that the i-th bird can pass before it has to rest is Ki-1.

输出

Your program should print exactly Q lines to the standard output. In the I-th line, it should specify the minimum number of tiresome flight legs of the i-th bird.

样例输入

9
4 6 3 6 3 7 2 6 5
2
2
5

样例输出

2
1


题解

单调队列优化dp

设f[i]表示跳到i的最小劳累值,那么有f[i]=f[j]+(height[i]>=height[j])

由于f[i]-f[j]最大为1,所以从f[k]=f[j]+x转移过来一定不是最优,即f小的更优。

同时应尽量让height[j]大,所以当f相同时,height更大的更优。

据此我们可以维护一个单调队列,其中f单调递增,f相同时height单调递减。

然后判断边界更新f并加入到队列中即可。

#include <cstdio>
int a[1000010] , q[1000010] , f[1000010];
bool cmp(int x , int y)
{
return f[x] == f[y] ? a[x] > a[y] : f[x] < f[y];
}
int main()
{
int n , i , m , k , l , r;
scanf("%d" , &n);
for(i = 1 ; i <= n ; i ++ ) scanf("%d" , &a[i]);
scanf("%d" , &m);
while(m -- )
{
scanf("%d" , &k);
l = r = q[1] = 1;
for(i = 2 ; i <= n ; i ++ )
{
while(l <= r && q[l] < i - k) l ++ ;
f[i] = f[q[l]] + (a[q[l]] <= a[i]);
while(l <= r && cmp(i , q[r])) r -- ;
q[++r] = i;
}
printf("%d\n" , f[n]);
}
return 0;
}