程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> codeforces 229/D 動態規劃

codeforces 229/D 動態規劃

編輯:C++入門知識

codeforces 229/D 動態規劃


 

D. Towers time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from left to right.

The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands i-th and put it on the top of either the (i - 1)-th tower (if it exists), or the (i + 1)-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1.

Help the mayor determine the minimum number of operations required to make the city beautiful.

Input

The first line contains a single integer n (1 ≤ n ≤ 5000) — the number of towers in the city. The next line contains n space-separated integers: the i-th number hi (1 ≤ hi ≤ 105) determines the height of the tower that is i-th (from left to right) in the initial tower sequence.

Output

Print a single integer — the minimum number of operations needed to make the city beautiful.

Sample test(s) input
5
8 2 7 3 1
output
3
input
3
5 2 1
output
2

題意:

 

這個城市有n座塔,為了美觀,需要後面的塔不能比前面的塔矮,所以需要你來整理,你的操作方式是可以把任意一個塔放到他相鄰的一座塔上,組成一座新塔,

注意只能移到相鄰的塔上,新塔還能繼續移動,問你最少多少步可以完成

思路:

一開始我天真的以為是貪心,想在O(n)的復雜度上解決他,代碼也寫出來了,過了很多組數據,CF給後台,當我看那組我WA的數據的時候,我才意識到我的思路是完全錯的,就扔掉了,過了好幾個月才撿起來想了個DP的解法:

二維DP,dp[i][j]:i表示第i座塔移動的j步,他能達到的最矮的情況,dp不斷更新,跑一遍O(n^2)能解決,

 

#include 
using namespace std;
int dp[5002][5002];//第i個塔,用了j步驟的高度,向前壓,向後壓
const int inf=0x7f7f7f7f;
class Solution
{
    int n,a[5002];
public:
    Solution(int _n):n(_n)
    {
        for(int i=0; i

 

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved