for (int i = 1; i <= n; i ++) { cin >> a[i]; s[i] += s[i - 1] + a[i]; }
memset(f, 0x3f, sizeof f); // 区间 DP 枚举套路:长度+左端点 for (int len = 1; len <= n; len ++) { // len表示[i, j]的元素个数 for (int i = 1; i + len - 1 <= n; i ++) { int j = i + len - 1; // 自动得到右端点 if (len == 1) { f[i][j] = 0; // 边界初始化 continue; }
for (int k = i; k <= j - 1; k ++) { // 必须满足k + 1 <= j f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + s[j] - s[i - 1]); } } }
intmain() { cin >> n; for (int i = 1; i <= n; i ++ ) cin >> w[i], w[i + n] = w[i];
for (int len = 3; len <= n + 1; len ++ ) for (int l = 1; l + len - 1 <= 2 * n; l ++ ) { int r = l + len - 1; // 省去了len=2(一个点)时初始化为0 for (int k = l + 1; k < r; k ++ ) f[l][r] = max(f[l][r], f[l][k] + f[k][r] + w[l] * w[k] * w[r]); }
int ans = 0; for(int i = 1; i <= n; i ++ ) ans = max(ans, f[i][i + n]); cout << ans << endl;
int k = root[l][r]; // cout << k << " "; // 前序遍历先输出根节点 dfs(l, k - 1); dfs(k + 1, r); }
intmain() { cin >> n; for (int i = 1; i <= n; i ++ ) cin >> w[i];
for (int len = 1; len <= n; len ++ ) for (int l = 1; l + len - 1 <= n; l ++ ) { int r = l + len - 1;
for (int k = l; k <= r; k ++ ) { int left = (k == l ? 1 : f[l][k - 1]); int right = (k == r ? 1 : f[k + 1][r]); int score = left * right + w[k]; // 计算加分 if (l == r) score = w[k]; if (f[l][r] < score) { f[l][r] = score; root[l][r] = k; // 记录节点 } } }
boolcmp(vector<int> &a, vector<int> &b) { if (a.size() != b.size()) return a.size() < b.size(); for (int i = a.size() - 1; i >= 0; i -- ) if (a[i] != b[i]) return a[i] < b[i]; returntrue; } vector<int> add(vector<int> a, vector<int> b) { vector<int> c; int t = 0; for (int i = 0; i < a.size() || i < b.size(); i ++ ) { if (i < a.size()) t += a[i]; if (i < b.size()) t += b[i]; c.push_back(t % 10); t /= 10; } while (t) c.push_back(t % 10), t /= 10; return c; } vector<int> mul(vector<int> a, LL b) { vector<int> c; LL t = 0; for (int i = 0; i < a.size(); i ++ ) { t += b * a[i]; c.push_back(t % 10); t /= 10; } while (t) c.push_back(t % 10), t /= 10; return c; }
intmain() { cin >> n; for (int i = 1; i <= n; i ++ ) cin >> w[i];
//此处初始状态f[l][l+1] = 0 初始就是空vector,不用额外设置 for (int len = 3; len <= n; len ++ ) for (int l = 1; l + len - 1 <= n; l ++ ) { int r = l + len - 1; for (int k = l + 1; k < r; k ++ ) { auto new_val = mul(mul({w[l]}, w[k]), w[r]); new_val = add(add(new_val, f[l][k]), f[k][r]); if (f[l][r].empty() || cmp(new_val, f[l][r])) f[l][r] = new_val; } }
auto ans = f[1][n]; for (int i = ans.size() - 1; i >= 0; i -- ) cout << ans[i]; return0; }