HDU4960 Another OCD Patient

来源:互联网 发布:同盾大数据 编辑:程序博客网 时间:2024/06/06 03:32


Problem Description

Xiaoji is an OCD (obsessive-compulsive disorder) patient. This morning, his children played with plasticene. They broke the plasticene into N pieces, and put them in a line. Each piece has a volume Vi. Since Xiaoji is an OCD patient, he can't stand with the disorder of the volume of the N pieces of plasticene. Now he wants to merge some successive pieces so that the volume in line is symmetrical! For example, (10, 20, 20, 10), (4,1,4) and (2) are symmetrical but (3,1,2), (3, 1, 1) and (1, 2, 1, 2) are not.

However, because Xiaoji's OCD is more and more serious, now he has a strange opinion that merging i successive pieces into one will cost ai. And he wants to achieve his goal with minimum cost. Can you help him?

By the way, if one piece is merged by Xiaoji, he would not use it to merge again. Don't ask why. You should know Xiaoji has an OCD.
 

Input
The input contains multiple test cases.

The first line of each case is an integer N (0 < N <= 5000), indicating the number of pieces in a line. The second line contains N integers Vi, volume of each piece (0 < Vi <=10^9). The third line contains N integers ai(0 < ai <=10000), and a1 is always 0.

The input is terminated by N = 0.
 

Output
Output one line containing the minimum cost of all operations Xiaoji needs.
 

Sample Input
56 2 8 7 10 5 2 10 200
 

Sample Output
10
Hint
In the sample, there is two ways to achieve Xiaoji's goal.[6 2 8 7 1] -> [8 8 7 1] -> [8 8 8] will cost 5 + 5 = 10.[6 2 8 7 1] -> [24] will cost 20.

dp问题,借鉴了别人写的比较好的代码,很容易理解:

#include <iostream>using namespace std;typedef __int64 LL;const int MAX = 5000+10;int dp[MAX][MAX],a[MAX],v[MAX];LL sum[MAX];LL min(LL a,LL b){return a<b ?a:b;}int dfs(int L,int R) {    if(L>=R) return 0;    if(~dp[L][R]) return dp[L][R];    LL sum1,sum2; int ans=a[R-L+1];    for(int i=L,j=R;i<j;) {        sum1=sum[i]-sum[L-1];        sum2=sum[R]-sum[j-1];        if(sum1 == sum2) {            ans = min(ans,dfs(i+1,j-1)+a[i-L+1]+a[R-j+1]);            i++;j--;        }        else if(sum1 > sum2) j--;        else i++;    }    return dp[L][R]=ans;}int main() {    int n;    while(scanf("%d",&n)&&n) {        memset(sum,0,sizeof(sum));        for(int i=1;i<=n;i++) {            scanf("%d",&v[i]);            sum[i] = sum[i-1]+v[i];        }        for(i=1;i<=n;i++) {            scanf("%d",&a[i]);        }        memset(dp,-1,sizeof(dp));        int ans=dfs(1,n);        printf("%d\n",ans);    }return 0;}


0 0