CodeForces - 574D - Bear and Blocks(双向 dp )

Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.

Limak will repeat the following operation till everything is destroyed.

Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.

Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

Input
The first line contains single integer n (1 ≤ n ≤ 105).

The second line contains n space-separated integers h1, h2, …, hn (1 ≤ hi ≤ 109) — sizes of towers.

Output
Print the number of operations needed to destroy all towers.

Examples
Input
6
2 1 4 6 2 2
Output
3
Input
7
3 3 3 1 3 3 3
Output
2
Note
The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.

在这里插入图片描述
After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.
题目链接
参考题解

给定一些柱体的高度,每一次都把裸露在外面的部分去掉。问一共需要多少次这样的操作才能把所有柱体全部去掉。

这个题目数据量比较大,1e5,所以想贪心,暴力什么的是不可能了。这个题目也是看题解才想到的,可以用dp来做。dp数组代表当前这一个柱体要完全消失需要多少次操作。每一个柱体要完全消失只有两种方式:
1、自己一层一层的消失;
2、旁边的消失之后下一个自己就消失了。
所以其中取最小的,然后左右各一次遍历dp就可以了。最后找到操作次数最多的那个便是。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 5;
int h[maxn], t[maxn];

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        int ans = -1;
        memset(t, 0, sizeof(t));

        for(int i = 1; i <= n; i++)
            scanf("%d", &h[i]);
        for(int i = 1; i <= n; i++)
            t[i] = min(h[i], t[i - 1] + 1); //自己一层一层消融或者旁边的消融,下一刻自己也全部消融
        for(int i = n; i >= 1; i--)
        {
            t[i] = min(t[i], t[i + 1] + 1);
            ans = max(ans, t[i]);
        }
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/82768288