Towers codeforce +dp

来源:互联网 发布:智慧芽数据库 编辑:程序博客网 时间:2024/06/07 00:03

The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goesi-th (from left to right) in the sequence equalshi. The city mayor decided to rebuild the city to make itbeautiful. 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 standsi-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 containsn 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 Input

Input
58 2 7 3 1
Output
3
Input
35 2 1
Output
2
解决方案:可推得递归方程:dp[i]=max(dp[j]+i-j-1,dp[i])&&last[j]<=sum[i]-sum[j];dp[i]代表前i个形成递增所需的最小步数,last[i]表示前i个的最高的塔的高度,sum[i],表示前i个塔总高度,每次选最优,并更新last[i],dp[i]。
code:
#include<iostream>#include<cstdio>#include<cstring>using namespace std;int last[5050],dp[5050],sum[5050];int N;int main(){    scanf("%d",&N);    for(int i=1;i<=N;i++){        int a;        scanf("%d",&a);        sum[i]+=sum[i-1]+a;        dp[i]=1<<30;        last[i]=1<<30;    }    for(int i=1;i<=N;i++)    for(int j=0;j<i;j++){        if(sum[i]-sum[j]>=last[j]&&dp[i]>=dp[j]+i-j-1){            dp[i]=dp[j]+i-j-1;            if(last[i]>sum[i]-sum[j])                last[i]=sum[i]-sum[j];        }    }    printf("%d\n",dp[N]);    return 0;}

0 0
原创粉丝点击