题目链接:http://poj.org/problem?id=1651
题解: 详情请看紫书P277。 对这题最大的感触是:中分(不一定平分)。
记忆化搜索:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define mp make_pair
#define ms(a, b) memset((a), (b), sizeof(a))
#define eps 0.0000001
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 100+10;
LL p[maxn], dp[maxn][maxn];
LL dfs(int i, int j)
{
if(dp[i][j]!=LNF) return dp[i][j];
if(i==j) return 0;
for(int k = i; k<j; k++)
dp[i][j] = min(dp[i][j], dfs(i,k) + dfs(k+1,j) + p[i-1]*p[k]*p[j]);
return dp[i][j];
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i<n; i++)
scanf("%lld",&p[i]);
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
dp[i][j] = LNF;
cout<<dfs(1,n-1)<<endl;
return 0;
}
递推:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define mp make_pair
#define ms(a, b) memset((a), (b), sizeof(a))
#define eps 0.0000001
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 100+10;
LL p[maxn], dp[maxn][maxn];
LL solve(int N)
{
for(int i = 1; i<=N; i++)
dp[i][i] = 0;
for(int len = 2; len<=N; len++)
{
for(int i = 1; i<=N-len+1; i++)
{
int j = i + len - 1;
for(int k = i; k<j; k++)
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + p[i-1]*p[k]*p[j]);
}
}
return dp[1][N];
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i<n; i++)
scanf("%lld",&p[i]);
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
dp[i][j] = LNF;
cout<<solve(n-1)<<endl;
return 0;
}