CF448C Painting Fence(遞迴+貪心)
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.
The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integersa1, a2, ..., an (1 ≤ ai ≤ 109).
Print a single integer — the minimum number of strokes needed to paint the whole fence.
5 2 2 1 2 1
3
2 2 2
2
1 5
1
可以橫著放也可以豎著放 我們需要在其中選擇最優的 當橫著放的時候需要 minh(區間中最小的高度)次 豎著放需要res(區間中木板個數)次
每次選擇的為min(res,minh) 當高度有0的時候需要從此處分開 向兩邊進行同樣的操作
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 5001;
int n;
int a[N];
int solve(int l,int r)
{
if(l>r)
return 0;
int minh=*min_element(a+l,a+r+1);//找到區間中最小元素的位置
int ret=r-l+1,tot=minh;
if(ret<minh){
for(int i=l;i<=r;i++)
a[i]=0;
return ret;
}
else{
for(int i=l;i<=r;i++)
a[i]-=minh;
int t=min_element(a+l,a+r+1)-a;
tot+=(solve(l,t-1)+solve(t+1,r));
}
return min(ret,tot);
}
int main()
{
while(cin>>n){
for(int i=0;i<n;i++)
cin>>a[i];
cout<<solve(0,n-1)<<endl;
}
return 0;
}
/*****
5
2 2 1 2 1
***/
相關文章
- Codeforces 448C. Painting FenceAI
- Codeforces 448C Painting Fence:分治AI
- Luogu P4425 轉盤 題解 [ 黑 ] [ 線段樹 ] [ 貪心 ] [ 遞迴 ]遞迴
- 演算法基礎 - 列舉/遞迴/動歸/深廣搜/二分/貪心演算法遞迴
- 貪心
- 反悔貪心
- Supermarket(貪心)
- 馬踏棋盤演算法(騎士周遊問題)----遞迴與貪心優化演算法演算法遞迴優化
- BZOJ 1724 [Usaco2006 Nov]Fence Repair 切割木板:貪心 優先佇列【合併果子】AI佇列
- 貪心模式記錄模式
- 貪心、構造合集
- 貪心演算法演算法
- 反悔貪心雜題
- 遞迴和尾遞迴遞迴
- 『無為則無心』Python函式 — 32、遞迴Python函式遞迴
- 2017廣東工業大學程式設計競賽決賽 題解&原始碼(A,數學解方程,B,貪心博弈,C,遞迴,D,水,E,貪心,面試題,F,貪心,列舉,LCA,G,dp,記憶化搜尋,H,思維題)...程式設計原始碼遞迴面試題
- Least Cost Bracket Sequence(貪心)ASTRacket
- 牛客 tokitsukaze and Soldier 貪心
- HDU 4550卡片遊戲(貪心)遊戲
- 24/03/20 貪心(一)
- 7.5 - 貪心篇完結
- 貪心 做題筆記筆記
- 「貪心」做題記錄
- 快速排序【遞迴】【非遞迴】排序遞迴
- 學一下貪心演算法-學一下貪心演算法演算法
- 貪心演算法(貪婪演算法,greedy algorithm)演算法Go
- HDU 5813 Elegant Construction (貪心)Struct
- 淺談貪心與動歸
- 貪心演算法Dijkstra演算法
- 貪心(入門簡單題)
- 9-貪心演算法演算法
- [反悔貪心] Add One 2
- 遞迴遞迴
- ACM(遞迴遞推—A)ACM遞迴
- 程式猿生存指南-63 貪心姑娘
- 演算法基礎–貪心策略演算法
- Moving Tables(貪心演算法)演算法
- 1413D. Shurikens(貪心,棧)3D