思路:
1. dp[k][i][j][s] 表示在前 i 个积木分成 k 堆,并且第 k 堆最上面的积木编号为 j,j 的 s 面朝上(s = 0, 1, 2);
2. 第 i 个积木有 3 种决策:
a. dp[k][i][i][t] = min(dp[k][i-1][j][s]); 放在第 k 堆;
b. dp[k][i][i][t] = min(dp[k-1][i-1][j][s]); 另起一堆;
c. dp[k][i][j][s] = dp[k][i-1][j][s]; 不参与;
3. 由于摆在上面的边要小于等于摆在下面积木的边,所以事先可以对 a, b, c 边从小到大排序下,判断的时候更加方便;
4. 对于循环中的 t, s 变量,则是控制上、下积木朝向的。我们每次交换边的值,只让 b, c 比较,使代码看起来更加清爽;
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 110;
int dp[MAXN][MAXN][MAXN][3];
int a[MAXN], b[MAXN], c[MAXN]; // 0 bc, 1 ac, 2 ab
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d%d%d", &a[i], &b[i], &c[i]);
if (a[i] > b[i]) swap(a[i], b[i]);
if (b[i] > c[i]) swap(b[i], c[i]);
if (a[i] > b[i]) swap(a[i], b[i]);
}
for (int k = 1; k <= m; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
for (int t = 0; t <= 2; t++) {
if (t == 1) swap(b[i], a[i]);
if (t == 2) swap(c[i], b[i]), swap(a[i], b[i]);
for (int s = 0; s <= 2; s++) {
if (s == 1) swap(b[j], a[j]);
if (s == 2) swap(c[j], b[j]), swap(a[j], b[j]);
if (b[i] <= b[j] && c[i] <= c[j])
dp[k][i][i][t] = max(dp[k][i][i][t], dp[k][i-1][j][s] + a[i]);
if (s == 2) swap(a[j], b[j]), swap(b[j], c[j]);
if (s == 1) swap(b[j], a[j]);
dp[k][i][i][t] = max(dp[k][i][i][t], dp[k-1][i-1][j][s] + a[i]);
dp[k][i][j][s] = dp[k][i-1][j][s];
}
if (t == 2) swap(a[i], b[i]), swap(c[i], b[i]);
if (t == 1) swap(b[i], a[i]);
}
}
}
}
int ans = 0;
for (int j = 1; j <= n; j++)
for (int s = 0; s <= 2; s++)
ans = max(ans, dp[m][n][j][s]);
printf("%d\n", ans);
return 0;
}