石子归并【动态规划】

http://codevs.cn/problem/1048/

#include
#include
using namespace std;
//状态转移方程:dp[i][j]=dp[i][k]+dp[k+1][j]+(w[i]+w[i+1]+...+w[j-1]+w[j]). 
int w[101];int n; 
int dp[101][101];
int pw[101];//记录前缀和 

int main(){
	cin>>n;
	memset(dp,0x3f,sizeof(dp));
	pw[0]=0;
	for(int i=1;i<=n;i++){
		cin>>w[i];
		dp[i][i]=0;
		pw[i]=pw[i-1];
		pw[i]+=w[i];
	}
	for(int len=2;len<=n;len++){
		for(int i=1;i<=n-len+1;i++){
			int j=i+len-1;
			int minn=0x3f3f3f3f;
			for(int k=i;k<=j;k++){
				minn=min(dp[i][k]+dp[k+1][j]+pw[j]-pw[i]+w[i],minn);
			}
			dp[i][j]=minn;
		} 
	}

	cout<

 

 

你可能感兴趣的:(石子归并【动态规划】)