codeforces 448C Painting Fence(分治)

来源:互联网 发布:如何ping ip 的端口 编辑:程序博客网 时间:2024/05/29 17:50

Bizon the Champion isn’t just attentive, he also is very hardworking.

Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.

Bizon the Champion bought a brush in the shop, the brush’s width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush’s full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

Input
The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, …, an (1 ≤ ai ≤ 10^9).

Output
Print a single integer — the minimum number of strokes needed to paint the whole fence.

Example
Input
5
2 2 1 2 1
Output
3
Input
2
2 2
Output
2
Input
1
5
Output
1
Note
In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.

In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.

In the third sample there is only one plank that can be painted using a single vertical stroke.

大致题意:有n块连着的木板,每个木板的高度为hi,你需要把这n块木板上色,每次上色你可以选择竖着刷完一块木板,或者横着刷一个高度单位的连续的木板(不能中间空着的不能跳跃),问最少需要刷几次。

思路:整体来看,总的有两种方法,一是全部竖着刷一遍,二是把共同的连续的高度横着刷需要的次数+剩下的不连续块需要刷的最小次数。取二者中较小的作为答案。而求剩下的不连续块的最小刷的次数也是如此来做。所以可以用分治递归来做,当不连续块的区间[l,r],l==r时返回1(此时只能选择竖着刷一次)。

代码如下

#include <cstdio>  #include <cstring>  #include <iostream> #include <algorithm>#include <map>   #include <cmath>using namespace std; int H[5005];#define INF 0x3fffffff  int n;int dfs(int l,int r)//区间[l,r]最少需要刷的次数{    int minn=INF;    int sum=0;    if(l>r)    return 0;    if(r==l)    return 1;    for(int i=l;i<=r;i++)//选择区间内连续的高度的最大值    minn=min(H[i],minn);    for(int i=l;i<=r;i++)//全刷上颜色    H[i]-=minn;    sum=minn;//所需minn次    for(int i=l;i<=r;i++)    {        while(H[i]==0&&i<=r)        i++;        int ll=i;        while(H[i]!=0&&i<=r)        i++;        int rr=i-1;        sum+=dfs(ll,rr);     }     return min(sum,r-l+1);}int main() {     scanf("%d",&n);    for(int i=1;i<=n;i++)    scanf("%d",&H[i]);    printf("%d",dfs(1,n));}
原创粉丝点击