CodeForces 448C-Painting Fence-贪心

来源:互联网 发布:学编程需要什么条件 编辑:程序博客网 时间:2024/06/11 17:17

问题描述:
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.
题目大意:
n个木板,给木板刷漆,刷子宽度为1,可以无限地刷连续的木板,问最少刷多少次
AC代码:

int h[6000],n;int minh(int be,int en)//找出区间[be,en]内的最小值,并返回该最小值{    int i,min=h[be];    for(i=be;i<=en;i++)    {        if(h[i]<min)            min=h[i];    }    return min;}int brush(int beg,int end)//求刷区间[beg,end]内的木板所需最少操作{    int i,j;    int ver=end-beg+1;//ver记录区间[beg,end]的长度    int shortest=minh(beg,end);//shortest记录区间[beg,end]内的最小值    for(i=beg;i<=end;i++)        h[i]-=shortest;//刷漆    int ans=shortest;//操作数等于shortest的值    for(i=beg;i<=end;i++)//遍历区间[beg,end]        if(h[i]!=0)//找到一个高度不为0的木板        {        //找出一个区间[ll,rr],区间内的木板的高度都大于0            int ll,rr;            ll=i;            j=i+1;            while(j<=end&&h[j]!=0)                j++;            rr=j-1;            ans+=brush(ll,rr);//递归求解        }    if(ans>ver)        ans=ver;    return ans;//返回ans与ver中的较小值}int main(){    int i;    //输入    scanf("%d",&n);    for(i=1;i<=n;i++)        scanf("%d",&h[i]);    //打印    printf("%d\n",brush(1,n));    return 0;}

解决方法:
我们可以竖着全部刷完。还可以横着刷,再将没刷过的小区间内的木板当成一个子问题,递归地求解。每次返回这两个方案所需操作数的较小值

原创粉丝点击