Luogu P1063 能量项链

题目描述

https://www.luogu.com.cn/problem/P1063

区间dp入门题

Solution

我们令f[i][j]表示将区间[i,j]合并的最大值

dp时枚举区间长度和左端点即可

时间复杂度 $O(n^3)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdio>
#define maxn 110
using namespace std;

int n, m, a[maxn];

int f[maxn * 2][maxn * 2];

int ans;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i], a[i + n] = a[i];
for (int l = 2; l <= n; ++l)
for (int i = 1; i + l - 1 <= 2 * n - 1; ++i) {
int j = i + l - 1;
for (int k = i; k < j; ++k) f[i][j] = max(f[i][j], f[i][k] + f[k + 1][j] + a[i] * a[k + 1] * a[j + 1]);
}
for (int i = 1; i <= n; ++i) ans = max(ans, f[i][i + n - 1]);
cout << ans << endl;
return 0;
}