Files
python/TangDou/AcWing/Section/320_dfs.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

34 lines
1004 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 210;
int n;
int a[N];
int f[N][N]; // 记忆化结果
// 计算l~r之间的结果值
int dfs(int l, int r) {
if (r == l) return 0; // 区间内有一个数字
if (r == l + 1) return (a[l] * a[r] * a[r + 1]); // 区间内有两个数字,a[r+1]就是破环成链的妙用
int &v = f[l][r]; // 准备记录结果
if (v) return v; // 如果计算过,则返回已经有的结果
// 枚举倒数第一个可能的结束位置
for (int k = l; k < r; k++)
v = max(v, dfs(l, k) + dfs(k + 1, r) + a[l] * a[k + 1] * a[r + 1]);
return v;
}
int main() {
scanf("%d", &n);
// 破环成链
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), a[i + n] = a[i];
// 以每个位置为起点,跑一遍dfs,找出最大值
int res = 0;
for (int i = 1; i <= n; i++) res = max(res, dfs(i, i + n - 1));
printf("%d", res);
return 0;
}