【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 2Output
3Input
7 3 3 3 1 3 3 3Output
2Note
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.
題目大意:
給你一個長度為N的一串序列,ai表示在這個位子上有一座高度為ai的木塊。
每次操作需要去掉所有這樣的木塊:
一個木塊如果上下左右有一個空白位子。
問一共需要操作幾次,使得整個序列變成空的。
解題報告:
? ? 其實也可以直接i分別從2和n-1開始,然后初始化的時候把dpl[1]和dpr[n]給初始化了。
? ? dp是真的難想啊!!有的題解說轉化為一個匹配最長遞增序列的題目,但我感覺還是用dp更方便理解一些。
? ? dpl[i]表示從左邊開始消除把第i列消完所需的最小時間,dpr表示從右邊開始消除的。很明顯可以看出來,我要銷毀第i列的格子,只有三種方法,要么是左邊是空的,要么是右邊是空的,要么就是從最頂上一層一層轉化過來,也就是用a[i]的時間。只有這三種狀態下才可以一次轉移到這一個狀態,也就是第i列全部被清空,那么我們現在要維護這個最小值,然后再遍歷每一個定點,取一個最大值,因為我們需要把所有的盒子都清空,所以我們需要取一個最大值,這個值就是最終的答案。
AC代碼:
#include<bits/stdc++.h>using namespace std; const int MAX = 1e5 + 5; int a[MAX]; int dpl[MAX],dpr[MAX]; int main() {int n;cin>>n;for(int i = 1; i<=n; i++) scanf("%d",a+i);dpl[0] = 0;dpr[n+1] = 0;for(int i = 1; i<=n; i++) dpl[i] = min(dpl[i-1] + 1, a[i]);for(int i = n; i>=1; i--) dpr[i] = min(dpr[i+1] + 1, a[i]);int ans = 0;for(int i = 1; i<=n; i++) {ans = max(ans,min(dpl[i],dpr[i]));}cout << ans << endl;return 0 ;}?
總結
以上是生活随笔為你收集整理的【CodeForces - 574D】Bear and Blocks (dp,思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑名单申请信用卡攻略 小编给你支几招
- 下一篇: 【CodeForces - 122B 】