给一串数, 拿出一个数i的代价是a[i-1]*a[i]*a[i+1], 第一个数和最后一个数不能拿, 求拿走剩下的数的代价的最小值。
#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <map> #include <set> #include <string> #include <queue> using namespace std; #define pb(x) push_back(x) #define ll long long #define mk(x, y) make_pair(x, y) #define lson l, m, rt<<1 #define mem(a) memset(a, 0, sizeof(a)) #define rson m+1, r, rt<<1|1 #define mem1(a) memset(a, -1, sizeof(a)) #define mem2(a) memset(a, 0x3f, sizeof(a)) #define rep(i, a, n) for(int i = a; i<n; i++) #define ull unsigned long long typedef pair<int, int> pll; const double PI = acos(-1.0); const double eps = 1e-8; const int mod = 1e9+7; const int inf = 1e7; const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int dp[105][105], a[105]; int dfs(int l, int r) { if(~dp[l][r]) return dp[l][r]; dp[l][r] = inf; if(r-l==1) return dp[l][r] = 0; if(r-l == 2) return dp[l][r] = a[l]*a[l+1]*a[r]; for(int i = l+1; i<r; i++) { dp[l][r] = min(dp[l][r], dfs(l, i)+dfs(i, r)+a[i]*a[l]*a[r]); } return dp[l][r]; } int main() { int n; while(cin>>n) { mem1(dp); for(int i = 1; i<=n; i++) scanf("%d", &a[i]); int ans = dfs(1, n); cout<<ans<<endl; } return 0; }