nyist 737 区间DP-石子合并 dfs

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=737

看了题解才有思路:http://blog.csdn.net/u012350533/article/details/17054711

点个赞~

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define inf 233333333
int n,a[205],sum[205];
int dp[205][205];
int dfs(int i, int j){ //返回合并[i,j]的最小值
	if(dp[i][j] < inf)return dp[i][j];
	if( i  >= j) return dp[i][j] = 0;
	if(i+1 == j) return dp[i][j] = a[i] + a[j];

	for(int p=i; p<j ;p++)
		dp[i][j] = min(dp[i][j], dfs(i,p) + dfs(p+1,j) + sum[j]-sum[i-1]);

	return dp[i][j];
}
int main(){
	int i, j;
	while(~scanf("%d",&n)){
		for(i=1;i<=n;i++)scanf("%d",&a[i]);
		sum[0] = 0;
		for(i=1;i<=n;i++)sum[i] = sum[i-1]+a[i];

		for(i=1;i<=n;i++)for(j=1;j<=n;j++) 
			dp[i][j] = inf;

		printf("%d\n",dfs(1, n));
	}
	return 0;
}


 

你可能感兴趣的:(nyist 737 区间DP-石子合并 dfs)