当前位置: 代码迷 >> 综合 >> poj 1738 An old Stone Game(区间dp 合并石子问题直线型)
  详细解决方案

poj 1738 An old Stone Game(区间dp 合并石子问题直线型)

热度:3   发布时间:2024-01-13 21:08:25.0

1、http://poj.org/problem?id=1738

参考百度文库:http://wenku.baidu.com/view/adac87bbfd0a79563c1e726a.html

2、

An old Stone Game
Time Limit: 5000MS   Memory Limit: 30000K
Total Submissions: 2278   Accepted: 543

Description

There is an old stone game.At the beginning of the game the player picks n(1<=n<=50000) piles of stones in a line. The goal is to merge the stones in one pile observing the following rules:
At each step of the game,the player can merge two adjoining piles to a new pile.The score is the number of stones in the new pile.
You are to write a program to determine the minimum of the total score.

Input

The input contains several test cases. The first line of each test case contains an integer n, denoting the number of piles. The following n integers describe the number of stones in each pile at the beginning of the game.
The last test case is followed by one zero.

Output

For each test case output the answer on a single line.You may assume the answer will not exceed 1000000000.

Sample Input

1
100
3
3 4 3
4
1 1 1 1
0

Sample Output

0
17
8

 3、wrong 代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 50005
#define MAX 0x7fffffff
int stone[N];
int sum[N];
int dp[N][N];
int main()
{int n,add;while(scanf("%d",&n)!=EOF){if(n==0)break;for(int i=0; i<n; i++)scanf("%d",&stone[i]);sum[0]=stone[0];for(int i=1;i<n;i++){sum[i]=sum[i-1]+stone[i];}for(int i=0;i<n;i++)dp[i][i]=0;for(int v=1;v<n;v++){for(int i=0;i<n-v;i++){int j=i+v;dp[i][j]=MAX;if(i>0)add=sum[j]-sum[i-1];elseadd=sum[j];for(int k=i;k<j;k++){dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+add);}}}printf("%d\n",dp[0][n-1]);}return 0;
}


 

  相关解决方案